N
N
nano_e_t_42019-08-18 17:58:50
Game development
nano_e_t_4, 2019-08-18 17:58:50

How to determine that the player is moving towards the object?

Hello everyone
Please tell me, who knows how I can determine whether the player is moving towards the cursor or moving in the opposite direction from it (the position of the cursor is constantly changing, the player is given a motion vector from the keyboard
) animation, in the opposite - another

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ronald McDonald, 2019-08-18
@Zoominger

1. Determine the position of the cursor and the position of the player at time X and find the length of the vector from these points;
2. Determine the position of the cursor and the player at the moment X + n and also find the length of the vector;
3. Compare the lengths of the vectors. If the second one is less, it moves to the cursor; if it is more, it leaves;
4. Spit in the face of those who say that a programmer does not need mathematics.

A
Ark Tarusov, 2019-08-18
@kreo_OL

Ronald McDonald painted everything correctly, but since this is a unity topic, where would it be without a ready-made code xD

private GameObject player;
        private float oldSqrMagnitude;
        private Camera camera => Camera.main;

        private void Update()
        {
            var newSqrMagnitude = (player.transform.position - camera.ScreenToWorldPoint(Input.mousePosition)).sqrMagnitude;
            if (newSqrMagnitude > oldSqrMagnitude)
            {
                Debug.Log("дальше");
            }
            else if (newSqrMagnitude < oldSqrMagnitude)
            {
                Debug.Log("ближе");
            }
            else
            {
                Debug.Log("стоит");
            }

            oldSqrMagnitude = newSqrMagnitude;
        }

However, keep in mind that it will react here even if the character is standing still, and only the mouse is moving.
I think it’s not difficult to add checks so that it is taken into account only when the character moves)
If this code is not so accurate for your purposes, then replace .sqrMagnitude with .magnitude
I would also recommend counting it less often than every frame) To do this, you can use FIxedUpdate, or a coroutine . Ideally, this would be considered only when changing the position of the mouse / character;)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question