Getting rid of 2D collision jitter
I'm very new to coding so this could be a completely wrong script. I'm trying to develop a top down 2D game. Now I've implemented basic movement after following a tutorial, but when I collide with my walls, there is significant jittering on my character, so much that the character will even rotate if colliding with the wall long enough. The player has both a box collider and Rigidbody 2D attached, and I have followed various tutorials and guides to get rid of this jitter, but no luck so far. I'll attach my code below:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour{
public Animator animator;
private Rigidbody2D rb2D;
public int speed;
public void Start()
{
speed = 5;
rb2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0.0f);
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Magnitude", movement.magnitude);
transform.position = transform.position + movement * speed * Time.deltaTime;
//rb2D.MovePosition(rb2D.position * speed * Time.fixedDeltaTime);
rb2D.MovePosition(new Vector3((transform.position.x + movement.x * speed * Time.deltaTime), (transform.position.y + movement.y * speed * Time.deltaTime),
(transform.position.magnitude + movement.magnitude * speed * Time.deltaTime)));
}
}
Answer by Kossuranta · Feb 08, 2019 at 07:35 PM
Mainly jitter in your code happens because you are moving player with transform.position, which doesn't care about physics (collisions) and it will just move the player inside a wall and then physics will keep pushing your player out of the wall.
In your current code you are moving player twice with two different ways. First you are giving its Transform new position on line 26. and then on line 30. you tell Rigidbody2D to move to new position. I also don't understand why you are trying to move the Rigidbody on Z axis by using magnitude?
Generally when you are working with physics like in here movement and collisions are part of physics, you should do that in FixedUpdate instead of Update.
Anyway here is fixed version that should work.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Animator animator;
public float speed = 5f;
private Rigidbody2D rb2D;
public void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
private Vector2 movement = Vector3.zero;
private void Update()
{
movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Magnitude", movement.magnitude);
}
private void FixedUpdate()
{
rb2D.MovePosition(rb2D.position + movement * speed * Time.fixedDeltaTime);
}
}
Hey man thanks for your reply, I've just had a chance to try your script and it works a charm, thank you very much. :)