Question by
AUNS-Ecosystem · May 26 at 01:19 PM ·
2dscripting problem
How to fix rigidbody2d glitch and random reset to starting position?
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: https://auns-ecosystem.itch.io/auns-rick-and-morty-browser
Here is the script for main char:
Code (CSharp): 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!
Comment