[英]Shooting a projectile but goes in wrong direction - 2D game
我正在尝试制作一个简单的游戏,当用户触摸屏幕时,我要射击弹丸,首先生成8个弹丸(子画面),而当用户触摸屏幕时,我希望顶部弹丸沿触摸方向飞行。 我能够做到这一点; 但是,每次拍摄时,弹丸的方向都错误,这是一张说明问题的图像。
显然,图像仍在此处,但是对象将继续飞行,直到它离开屏幕然后被破坏为止。
这是处理此问题的代码段
GameplayController.cs
if (Input.GetMouseButtonDown(0))
{
Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
position = Camera.main.ScreenToWorldPoint(position);
GameObject target;
target = new GameObject();
target.transform.position = position;
Arrow comp = currentArrows[0].GetComponent<Arrow>();
comp.setTarget(target.transform);
comp.GetComponent<Arrow>().arrowSpeed = 12;
comp.GetComponent<Arrow>().shoot = true;
currentArrows.RemoveAt(0);
Destroy(target);
}
我知道我在这里得到鼠标输入而不是电话触摸,这对我来说很好,以后我将其转换为触摸输入。
Arrow.cs
public bool shoot = false;
public float arrowSpeed = 0.0f;
public Vector3 myDir;
public float speed = 30.0f;
private Transform target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(shoot)
{
transform.position += transform.right * arrowSpeed * Time.deltaTime;
}
}
public void setTarget(Transform targetTransform)
{
this.target = targetTransform;
Vector3 vectorToTarget = target.position - transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}
private void OnBecameInvisible()
{
print("Disappeared");
Destroy(gameObject);
Gameplay.instance.isShooting = false;
}
Vector3位置=新的Vector3(Input.mousePosition.x,Input.mousePosition.y,0);
我认为您的问题是您通过单击获取屏幕坐标,而不是世界坐标,这实际上是两件事。 为了正确地引导弹丸,您需要像这里一样将屏幕坐标转换为世界。
接下来是如何移动弹丸:
transform.position += transform.right * arrowSpeed * Time.deltaTime;
您正在将射弹向右移动,然后以某种方式旋转它。 也许您应该尝试使用Vector3.Lerp来移动它,这将变得更加容易,并使用Transform.LookAt对其进行旋转。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.