Vector3.MoveTowards jumps during first move

Ok. I have scratched my head long enough. I am having an ID10T error. I am trying to use Vector3.MoveTowards to move my character on a grid. My script works just as I expect it to work after the first move. The player moves smoothly on the X or Y axis from one grid cell to the next and always stops at exactly in the grid. However, on the first press of the movement keys the MoveToward is telling the player transform to move to the next cell. I have posted my feeble attempt at debugging this issue. As you can see I inserted a log before the MoveTowards and after. In frame 993, moves one full cell in the MoveTowards. I’m sure I am missing something simple, but I can’t figure it out. Any help would be appreciated.

Thanks

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
  /*  private const string IS_WALKING_SIDE = "IsWalkingSide";
    private const string IS_WALKING_UP = "IsWalkingUp";
    private const string IS_WALKING_DOWN = "IsWalkingDown";

    private const int RIGHT = 1;
    private const int LEFT = -1;
    private const int UP = 1;
    private const int DOWN = -1;*/

    [SerializeField] private float _speed;
    [SerializeField] private Transform _movePoint;
    [SerializeField] private LayerMask _obstacles;

    private PlayerControls _playerControls;
    private Vector2 _playerMovement;
    private Animator _animator;
    private SpriteRenderer _spriteRenderer;
    private int frameCount = 0;


    private void Awake()
    {
        _playerControls = new PlayerControls();
     //   _animator = GetComponentInChildren<Animator>();
     //   _spriteRenderer = GetComponentInChildren<SpriteRenderer>();
        _movePoint.parent = null;
        _movePoint.position = transform.position;
    }

    private void OnEnable()
    {
        _playerControls.Player.Enable();
    }

    private void OnDisable()
    {
        _playerControls.Player.Disable();
    }

    private void Update()
    {
        MovePlayer();
    }

    private void MovePlayer()
    {
        frameCount++;
        Debug.Log(frameCount +". I want to move from " + transform.position + " to " + _movePoint.position + " by " + _speed * Time.deltaTime + "each step.");

        transform.position = Vector3.MoveTowards(transform.position, _movePoint.position, _speed * Time.deltaTime);

        Debug.Log(frameCount + ". I want to move from " + transform.position + " to " + _movePoint.position + " by " + _speed * Time.deltaTime + "each step.");

        if (Vector3.Distance(transform.position, _movePoint.position) <= .05f)
        {
            _playerMovement = _playerControls.Player.Move.ReadValue<Vector2>();
            if (Mathf.Abs(_playerMovement.x) == 1f)
            {
                Vector3 checkPosition = _movePoint.position + new Vector3(_playerMovement.x, 0f, 0f);
                Vector2 origin = transform.position;
                RaycastHit2D hit = Physics2D.Raycast(origin, _playerMovement, 1f, _obstacles);


                if (hit.collider == null)
                {
                    _movePoint.position = checkPosition;
                }
            }
            if (Mathf.Abs(_playerMovement.y) == 1f)
            {
                Vector3 checkPosition = _movePoint.position + new Vector3(0f, _playerMovement.y, 0f);
                Vector2 origin = transform.position;
                RaycastHit2D hit = Physics2D.Raycast(origin, _playerMovement, 1f, _obstacles);

                if (hit.collider == null)
                {
                    _movePoint.position = checkPosition;
                }
            }
        }
    }
}

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

I see you at least might have started them, but something happened, perhaps interacting with the graphic??

While scratching your head is certainly an important PART of debugging, it isn’t debugging.

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

If you find something and it still doesn’t make sense, here is how to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to documentation you used to cross-check your work (CRITICAL!!!)

Thanks for your response. I am a big fan of debug.log. The code I posted doesn’t show all of the fifteen or twenty debug.logs I had put in to narrow it down to the fact that the transform.position is being updated in line 53 from the start position to one full position in whichever direction I direct the player to move Every move after than I can see the transform moving incrementally to the next position but on the first move input the transform jumps from the start position one full cell to the right which results in “studder step” as it would get hung on the collider on the block in the adjacent cell before the block could register the collision and shut off the collider and change the sprite. I removed the extra debug.logs to get a clean console report to show the changing of transform.position for .x = -6 to .x = -5 in one frame across the Vector3.MoveTowards in line 53.

I went back and scratched my head a little more (read added debug.logs). I also refactored the code to put the trigger event on the player. I am posting both scripts. I have eliminated everything from the scene except the camera, light, player, and 1x1 GameObjects with 1x1 colliders set to Is Trigger. When my player collider collides with the first gameobject it stops momentarily then jumps to the final position. When the player moves to any additional cells, it moves smoothly. When I remove the call to the GroundController script inside the trigger event, the player behaves as expected on the first move. If I deactivate the collider on the 1x1 block it behaves as expected but since there is no trigger it does not active the GroundController script. Here is the console log.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;


public class PlayerController : MonoBehaviour
{
    private const string IS_WALKING_SIDE = "IsWalkingSide";
    private const string IS_WALKING_UP = "IsWalkingUp";
    private const string IS_WALKING_DOWN = "IsWalkingDown";

    private const int RIGHT = 1;
    private const int LEFT = -1;
    private const int UP = 1;
    private const int DOWN = -1;

    [SerializeField] private float _speed;
    [SerializeField] private Transform _movePoint;
    [SerializeField] private LayerMask _obstacles;

    private PlayerControls _playerControls;
    private Vector2 _playerMovement;
    private Animator _animator;
    private SpriteRenderer _spriteRenderer;
    private int frameCount = 0;


    private void Awake()
    {
        _playerControls = new PlayerControls();
        _animator = GetComponentInChildren<Animator>();
        _spriteRenderer = GetComponentInChildren<SpriteRenderer>();
        _movePoint.parent = null;
        _movePoint.position = transform.position;
    }

    private void OnEnable()
    {
        _playerControls.Player.Enable();
    }

    private void OnDisable()
    {
        _playerControls.Player.Disable();
    }

    private void Update()
    {
        MovePlayer();
    }

    private void MovePlayer()
    {
        frameCount++;
        Debug.Log(frameCount +". I want to move from " + transform.position + " to " + _movePoint.position + " by " + _speed * Time.deltaTime + "each step.");

        transform.position = Vector3.MoveTowards(transform.position, _movePoint.position, _speed * Time.deltaTime);

        Debug.Log(frameCount + ". I want to move from " + transform.position + " to " + _movePoint.position + " by " + _speed * Time.deltaTime + "each step.");

        if (Vector3.Distance(transform.position, _movePoint.position) <= .05f)
        {
            _playerMovement = _playerControls.Player.Move.ReadValue<Vector2>();
            if (Mathf.Abs(_playerMovement.x) == 1f)
            {
                Vector3 checkPosition = _movePoint.position + new Vector3(_playerMovement.x, 0f, 0f);
                Vector2 origin = transform.position;
                RaycastHit2D hit = Physics2D.Raycast(origin, _playerMovement, 1f, _obstacles);


                if (hit.collider == null)
                {
                    _movePoint.position = checkPosition;
                }
            }
            if (Mathf.Abs(_playerMovement.y) == 1f)
            {
                Vector3 checkPosition = _movePoint.position + new Vector3(0f, _playerMovement.y, 0f);
                Vector2 origin = transform.position;
                RaycastHit2D hit = Physics2D.Raycast(origin, _playerMovement, 1f, _obstacles);

                if (hit.collider == null)
                {
                    _movePoint.position = checkPosition;
                }
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log("I hit: " + other.name);
        other.GetComponent<GroundController>().MineNode();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.Universal;

public class GroundController : MonoBehaviour
{
    private const string PLAYER = "Player";

    [SerializeField] private int miningCost;
    [SerializeField] private Sprite dirtSprite;
    [SerializeField] private Sprite floorSprite;
    [SerializeField] bool floorCovered;

    private SpriteRenderer spriteRender;
    private Light2D floorLight;
    private Collider2D thisCollider;

    private void Awake()
    {
        spriteRender = GetComponent<SpriteRenderer>();
        floorLight = GetComponent<Light2D>();
        thisCollider = GetComponent<Collider2D>();

        if(floorCovered)
        {
            spriteRender.sprite = dirtSprite;
            floorLight.enabled = false;
          //  thisCollider.enabled = true;
        }
        else
        {
            spriteRender.sprite = floorSprite;
            floorLight.enabled = true;
         //   thisCollider.enabled = false;
        }
    }

    public void MineNode ()
    {
        Debug.Log("Turning off collider");
            thisCollider.enabled = false;
        Debug.Log("Switching sprite");
            spriteRender.sprite = floorSprite;
        Debug.Log("Turning on floor light.");
            floorLight.enabled = true;
    }
}

Right away this is suspect:

Never test floating point (float) quantities for equality / inequality. Here’s why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

https://discussions.unity.com/t/851400/4

https://discussions.unity.com/t/843503/4

“Think of [floating point] as JPEG of numbers.” - orionsyndrome on the Unity3D Forums