Stuck figuring out how to push a GameObject using mouse position angle

Hi everybody, I’m fairly new to Unity and stuck trying to figure out some practice gameplay I’d like to script.

The gameplay is very simple. If I tap (or click) on an angle relative to the main character, he will bounce in the opposite direction. The player doesn’t necessarily have to touch the circle, I just want to consider the angle of the tap/click.

I made a few ugly drawings to explain better, hopefully they make sense:

And of course the same goes in every angle:

I’ve learned how to make a GameObject move towards the area I click:

    Vector3 dir = Input.mousePosition - newPosition;
    float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;

But I guess what i’m looking for is the inverse of this, and I can’t figure out how to do it :frowning: It’s a 2D game I and was thinking of using the RigidBody2D in order to use force. Thanks in advance!

Well it’s easy enough to invert the angle (just stick a “-” before Mathf.Atan2, or alternatively, swap tho order of the subtraction in line 2).

However you don’t actually need the angle to do what you’re wanting. You want to apply a force to the player, and a force is defined in terms of X and Y. You already have those in “dir” as of line 2. (Though what you have there is a vector that points towards the mouse position; you probably want to swap that subtraction, so it points away from the mouse, towards the player, instead.)

2 Likes

Thank you very much Joe, that definitely did it. Also added drag so the GameObject slows down. I’m doing all this in the Update method though, perhaps since it’s a RigidBody, I should update in FixedUpdate.

Thanks again Joe.

        Vector3 dir = Vector3.zero;

        if (Input.GetMouseButton (0)) {
            rigidBody.AddForce (Vector2.zero);
            rigidBody.velocity = Vector2.zero;

            dir = Input.mousePosition - newPosition;
            float angle = Mathf.Atan2 (-dir.y, -dir.x) * Mathf.Rad2Deg;

            transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);        
        }
            
        dir.Normalize ();
      
        rigidBody.AddForce (-dir * 40.0f, ForceMode2D.Impulse);
1 Like