简体   繁体   English

改变弹丸角度

[英]Change projectile angle

I'm trying to add accuracy to my game. 我正在尝试提高游戏的准确性。 Currently my player will always fire directly ahead (which is pointing towards the mouse cursor). 目前,我的播放器将始终直接向前方射击(指向鼠标光标)。 I would like to offset that firing angle by x degrees. 我想将该射击角度偏移x度。

My firing script currently looks like this : 我的触发脚本当前如下所示:

nextFire = Time.time + bulletConfig.TimeBetweenShots;
var offset = new Vector3(0, 0, 0);
var grid = GameObject.FindObjectOfType<Grid>();
var proj = Instantiate(projectile, transform.position, Quaternion.identity, grid.transform);
proj.transform.position = transform.position + offset;
proj.transform.rotation = transform.rotation;
print(proj.transform.rotation);

var controller = proj.GetComponent<BulletController>();
if (controller != null)
{
    controller.Fire(bulletConfig);
}

Destroy(proj, bulletConfig.DestroyTime);

The core of my problem is that I don't know how to add degrees to a vector3, without some complicated trigonometry. 我的问题的核心是,我不知道如何在没有复杂三角函数的情况下向vector3添加度。

Any ideas? 有任何想法吗?

As mentioned in the comment: 如评论中所述:

The documentation for Transform.rotate state: "To rotate an object, use Transform.Rotate ." Transform.rotate状态的文档: “要旋转对象,请使用Transform.Rotate 。”

Modifying your example this would look like this: 修改示例,如下所示:

// -- snipped for brevity
var proj = Instantiate(projectile, transform.position, Quaternion.identity, grid.transform);
proj.transform.position = transform.position + offset;
proj.transform.rotation = transform.rotation;
// Using the second overload of Transform.Rotate
float exampleOffsetAngle = 1.0f;
proj.transform.Rotate(exampleOffsetAngle, 0.0f, 0.0f);
print(proj.transform.rotation);
// -- snipped for brevity

For more examples and usage of the other overloads please refer to the official docs: https://docs.unity3d.com/ScriptReference/Transform.Rotate.html 有关其他重载的更多示例和用法,请参考官方文档: https : //docs.unity3d.com/ScriptReference/Transform.Rotate.html

Float degrees = 5;
Quaternion q = Quaternion.AngleAxis(Vector3.right, degrees);
proj.transform.rotation = q * proj.transform.rotation;
// Alternatively, if you have a vector vecToRotate:
vecToRotate = q * vecToRotate;

This will move it up by 5 degrees. 这会将其向上移动5度。 Use -5 for down. 使用-5降低。 Use something other than Vector3.right for other directions. Vector3.right的其他东西用于其他方向。

Trigonometry is not exactly complicated, especially not when you have a transformation object that can do the computation for you. 三角函数并不十分复杂,尤其是当您有一个可以为您进行计算的变换对象时。 "Adding degrees" amounts to rotating the transform of your projectile with the Rotate function. “增加度”等于使用“ 旋转”功能旋转弹丸的变换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM