Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

unity3d - 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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...