Quantcast
Channel: Answers by "IvovdMarel"
Viewing all articles
Browse latest Browse all 145

Answer by IvovdMarel

$
0
0
Hey Falconstrike! On your post: I recommend in the future to provide a bit more context to your problem. You can share your own code snippets, and explain in more detail what part is not working (e.g. error message, moving in the wrong direction, not moving at all?). As to your question, you can see this code snippet that has the feature that you are describing. Hopefully you can make sense of it through the comments. public class ShootToMouse : MonoBehaviour { public float forceAmount = 100; // Update is called once per frame void Update() { //If left mouse button is pressed if (Input.GetMouseButtonDown(0)) { //Get the position of this object in screen-coordinates Vector3 posInScreen = Camera.main.WorldToScreenPoint(transform.position); //You can calculate the direction from point A to point B using Vector3 dirAtoB = B - A; Vector3 dirToMouse = Input.mousePosition - posInScreen; //We normalize the direction (= make length of 1). This is to avoid the object moving with greater force when I click further away dirToMouse.Normalize(); //Adding the force to the 2D Rigidbody, multiplied by forceAmount, which can be set in the Inspector GetComponent().AddForce(dirToMouse * forceAmount); } } }

Viewing all articles
Browse latest Browse all 145

Trending Articles