xqz
xqz

Reputation: 41

Unity3D How to make object go away form mouse click position 2D

Im thinking about it two days. I still did not made any progress. I wonder how to do that objects fly away from mouse click position in 2D view?

I tried like that:

        pos = Input.mousePosition;
        Vector3 realWorldPos = Camera.main.ScreenToViewportPoint(pos);
        print("MOuse pos: " + realWorldPos);

        //print(realWorldPos);
        Vector3 velo = GetComponent<Rigidbody2D>().velocity;

        if (realWorldPos.x < 0.5)
        {
            velo = new Vector3((realWorldPos.x * speed), velo.y);
        }
        else if(realWorldPos.x > 0.5)
        {
            velo = new Vector3((realWorldPos.x * speed) * (-1), velo.y);
        }
        if (realWorldPos.y < 0.5)
        {
            velo = new Vector3(velo.x, realWorldPos.y * speed);
        }
        else if (realWorldPos.y > 0.5)
        {
            velo = new Vector3(velo.x, (realWorldPos.y * speed) * (-1));
        }

        GetComponent<Rigidbody2D>().velocity = velo;

But it doesnt work as I want.

Is it possible to do this?

Upvotes: 0

Views: 1244

Answers (1)

Gunnar B.
Gunnar B.

Reputation: 2989

For this to work your Rigidbody2D must have Gravity Scale set to 0.

This is a simple test code that works for me, is placed on a sprite object:

public class PushPlayer : MonoBehaviour
{
    public float pushPower = 50.0f;

    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Vector3 dir = transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
            dir = dir.normalized;

            rb.AddForce(dir * pushPower, ForceMode2D.Force);

            // as alternative:
            rb.velocity = dir * pushPower;
        }
    }
}

You need to adjust the values a bit, also in the regidbody (like drag) to get it the way you want.

Edit:

transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition): calculate the directional vector from the mouse position to the player position (have a look a vector algebra if you are not familiar with this) which is the direction away from the click (in a straight line).

dir.normalized: this shortens the vector to a length (= magnitude) of 1 (again have a look at vectors) so it really is just a direction. You could omit this and reduce the factor, but doing it this way your factor equals the force you use.

Upvotes: 2

Related Questions