Glitching 2D sprite OnMouseDrag and randomly resetting to initial position on MouseUp

I’m working on this Rick and Morty inspired 2D aim to shoot game. When you press drag back to aim the sprite glitches towards the initial position.

Also sometimes character randomly jumps back to initial position on release.

Here is the link to the game on itch.io: AUNS Rick and Morty Browser (PC/Laptop) by AUNS Ecosystem

Here is the script for main char:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Rick : MonoBehaviour

{
    [SerializeField] float _launchForce = 500;
    [SerializeField] float _maxDragDistance = 5;

    Vector2 _startPosition;
    Rigidbody2D _rigidbody2D;
    SpriteRenderer _spriteRenderer;
    private bool _birdWasLaunched;
    private float _timeSittingAround;

    void Awake()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        _spriteRenderer = GetComponent<SpriteRenderer>();
        _rigidbody2D.gravityScale = 2;
    }

    void Start()
    {
        _startPosition = _rigidbody2D.position;
        _rigidbody2D.isKinematic = true;
    }
    void OnMouseDown()
    {
        _spriteRenderer.color = new Color(0, 1, 1);
        GetComponent<LineRenderer>().enabled = true;
    }

    void OnMouseUp()
    {
        Vector2 currentPosition = _rigidbody2D.position;
        Vector2 direction = _startPosition - currentPosition;
        direction.Normalize();
   
    Vector2 directionToInitialPosition = _startPosition - currentPosition;
    _rigidbody2D.isKinematic = false;
    _rigidbody2D.AddForce(directionToInitialPosition * _launchForce);

        _spriteRenderer.color = Color.white;
        GetComponent<LineRenderer>().enabled = false;
    }

    void OnMouseDrag()
    {
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector2 desiredPosition = mousePosition;
        _rigidbody2D.isKinematic = true;

            float distance = Vector2.Distance(desiredPosition, _startPosition);
            if (distance > _maxDragDistance)
            {
                Vector2 direction = desiredPosition - _startPosition;
                direction.Normalize();
                desiredPosition = _startPosition + (direction * _maxDragDistance);
            }

            if (desiredPosition.x > _startPosition.x)
            desiredPosition.x = _startPosition.x;

        _rigidbody2D.position = desiredPosition;
    }

    void Update()
    {
             GetComponent<LineRenderer>().SetPosition(0, _startPosition);
     GetComponent<LineRenderer>().SetPosition(1, _rigidbody2D.position);
     if (_birdWasLaunched &&
        _rigidbody2D.velocity.magnitude <= 0.1)

        {_timeSittingAround += Time.deltaTime;
        }

     if (
     _timeSittingAround > 3)

     {
         string currentSceneName = SceneManager.GetActiveScene().name;
         SceneManager.LoadScene(currentSceneName);
     }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        StartCoroutine(ResetAfterDelay());
    }

    IEnumerator ResetAfterDelay()
    {
        yield return new WaitForSeconds(4);
         _rigidbody2D.position = _startPosition;
        _rigidbody2D.isKinematic = true;
        _rigidbody2D.velocity = Vector2.zero;
   
    }

}

Any help would super appreciated on this!

Might be a weird timing issue with the various OnMouse callbacks, as they happen unsynchronized with physics. To remedy that you would only note the event that happened, then process it in FixedUpdate(), which is where ALL Physics stuff should really be done. Here’s why:

Here is some timing diagram help:

Good discussion on Update() vs FixedUpdate() timing:

If it isn’t that, perhaps your ResetAfterDelay coroutine wait expires and line 98 and onwards gets called? Just a rando guess.

You only have so many “set position” places, put Debug.Log() on all of em, see what they are doing. Shouldn’t be long before you see who is pushing it wrong.

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

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 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.

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.

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: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

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:

1 Like