统一:如何对物体的速度应用旋转?



我正在 Unity 上制作自上而下的射击游戏,我需要实现霰弹枪,一次将释放 5 发子弹,接下来每发子弹的旋转度将比以前少 10 度(总共从 20 度到 -20 度(。在火点上实例化子弹,速度通过附加到子弹预制件的子弹脚本应用于它。我也在实例化方法中应用旋转,但子弹只是围绕自身旋转,而不是方向飞行。 拍摄代码:

Vector2 mouseScreenPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (mouseScreenPosition - (Vector2) transform.position).normalized;
transform.up = direction;
GameObject newBullet1 = Instantiate(bullet, firePoint.position, Quaternion.Euler(0f, 0f, 20f)) as GameObject;
newBullet1.GetComponent<Bullet>().direction = direction;
GameObject newBullet2 = Instantiate(bullet, firePoint.position, Quaternion.Euler(0f, 0f, 10f)) as GameObject;
newBullet2.GetComponent<Bullet>().direction = direction;

项目符号代码:

public Vector3 direction;
public float bulletSpeed;
void Update () {
GetComponent<Rigidbody2D>().velocity = new Vector3 (direction.x, direction.y, transform.position.z) * bulletSpeed;
}

您需要将旋转应用于每个项目符号的方向矢量。矢量旋转的公式是... x1 = x0*余弦(角度( - y0*正弦(角度(; y1 = x0*正弦(角度( + y0*余弦(角度(;

Vector2 direction10 = new Vector2(direction.x*Mathf.cos(10*Mathf.Deg2Rad) - direction.y*Mathf.sin(10*Mathf.Deg2Rad), direction.x*Mathf.sin(10*Mathf.Deg2Rad) + direction.y*Mathf.cos(10*Mathf.Deg2Rad));
Vector2 direction20 = new Vector2(direction.x*Mathf.cos(20*Mathf.Deg2Rad) - direction.y*Mathf.sin(20*Mathf.Deg2Rad), direction.x*Mathf.sin(20*Mathf.Deg2Rad) + direction.y*Mathf.cos(20*Mathf.Deg2Rad));
newBullet2.GetComponent<Bullet>().direction = direction10;
newBullet3.GetComponent<Bullet>().direction = direction20;
... //etc

可能可以通过循环来做这个清洁器。

最新更新