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