简体   繁体   中英

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). 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); with 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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