简体   繁体   English

让object匀速滑翔到鼠标 Unity C#

[英]Let object glide to mouse with constant speed Unity C#

I have a bullet object, that needs to glide to the mouse when the mouse is pressed (but should stop when it is released).我有一个子弹 object,它需要在按下鼠标时滑向鼠标(但释放时应该停止)。 I have tried multiple approaches, but every time the bullet accelerates, and makes circles around the mouse in a ellipse form (I also have gravity).我尝试了多种方法,但每次子弹加速时,都会以椭圆形围绕鼠标转圈(我也有重力)。 How can I get it to just move towards the mouse at a constant speed?我怎样才能让它以恒定的速度向鼠标移动?

This is my code:这是我的代码:

using UnityEngine;
public class Bullet : MonoBehaviour {
    public Rigidbody rigidbody;
    void Start() {
        rigidbody = GetComponent<Rigidbody>();
        rigidbody.useGravity = false;
        rigidbody.velocity = new Vector3(0, -0.3F, 0);
    }
    float getX(Vector3 transform_pos, Vector3 mouse_pos) {
        float tx = transform_pos.x;
        float mx = mouse_pos.x;
        if (tx == mx) { return 0;
        } else if (tx > mx) { return -1;
        } else if (tx < mx ) { return 1;
        }else { return 0; }
    }
    void Update() {
        if (Input.GetMouseButton(0)) {
            Vector3 mouse_pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            transform.LookAt(mouse_pos);
            float x = getX(transform.position, mouse_pos);
            float y = transform.position.y > mouse_pos.y ? -0.03F : 0.03F;
            rigidbody.AddForce(new Vector3(x, 0, transform.position.z), ForceMode.VelocityChange);
            Debug.Log(x.ToString() + y.ToString());
        }
        if (transform.position.y < -5 | transform.position.y > 5) {
            Destroy(transform.gameObject);
        }
        rigidbody.AddForce(Vector3.down, ForceMode.Force);
    }
}

I tried a bit more, and found out, that using rigidbody.velocity() is better than rigidbody.AddForce() , so replace rigidbody.AddForce(new Vector3(x, 0, transform.position.z), ForceMode.VelocityChange);我尝试了更多,发现使用rigidbody.velocity()比使用rigidbody.AddForce( rigidbody.AddForce()更好,所以替换rigidbody.AddForce(new Vector3(x, 0, transform.position.z), ForceMode.VelocityChange); with rigidbody.velocity = new Vector3(x, y, transform.position.z);rigidbody.velocity = new Vector3(x, y, transform.position.z); (replace x and y with the velocity and it should work. Note that this replaces the velocity, so all the movement will be stopped) (将xy替换为速度,它应该可以工作。请注意,这会替换速度,因此所有运动都将停止)

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

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