How to make my 2d object keep moving after it reaches the mouse position

Hello guys! I’m trying to build a snake game like slither .io

In the fixedUpdate() I have this line of code:

      private void FixedUpdate()
        Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 temp2 = new Vector2(temp.x, temp.y);
            transform.position = Vector2.MoveTowards(transform.position, temp2, 2f * Time.fixedDeltaTime);

Which makes the ‘head’ of the snakes follow the mouse. But when the distance between the head and the mouse is zero, it freezes. I want it to continue moving in the direction it was heading.

I tried making an empty object always in front of the mouse - which failed, I’m not sure as how to implement it. I tried taking the delta of the mouse and head distance and adding it to the object which didn’t work as planned. I also thought about shooting a ray forward and when the distance is zero or less than 0.1f, to keep moving along the ray. But I’m not sure how to implement this. Any ideas?

Hi @anarhist1994
use this

if(temp2 != (Vector2)transform.localPosition){
 // ur code

Hey, this code will do exactly what you want, plus it will allow you to adjust the speed from the inspector!

using UnityEngine;

public class MoveTowardsMouse : MonoBehaviour {
    public float moveSpeed = 4f;

    private Vector2 previousMousePosition;
    private Vector2 moveDirection;

    private void FixedUpdate () {
        Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 newMoveDirection = mouseWorldPosition - ((Vector2)transform.position);

        // Ensures that the new direction for the object to move in is only assigned if the mouse changes position.
        if (Overlap(previousMousePosition, mouseWorldPosition, 0.01f) == false) {
            moveDirection = newMoveDirection;

        // Ensures that the object moves at the same speed regardless of how far away the mouse is from it.
        float totalMoveDirection = Mathf.Abs(moveDirection.x) + Mathf.Abs(moveDirection.y);
        transform.position = Vector2.Lerp(transform.position, ((Vector2)transform.position) + moveDirection, (moveSpeed / totalMoveDirection) * Time.fixedDeltaTime);

        previousMousePosition = mouseWorldPosition;

        // Tests whether or not the two points overlap.
    private bool Overlap (Vector2 a, Vector2 b, float radius) {
        return ((Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y))) <= radius;

Hope this helps!