When I move my 2d character(a circle, for now) into a rock(it has a box collider 2d), it does that weird thing where it kinda glitches through then comes back out and looks very jittery, how do i fix that?
heres my movement code btw:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed;
[SerializeField]
float leftBorder;
[SerializeField]
float rightBorder;
[SerializeField]
float topBorder;
[SerializeField]
float bottomBorder;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Move();
Clamp();
}
void Move()
{
if(Input.GetKey(KeyCode.W))
{
transform.Translate(0, moveSpeed * Time.deltaTime, 0);
}
if(Input.GetKey(KeyCode.S))
{
transform.Translate(0, -moveSpeed * Time.deltaTime, 0);
}
if(Input.GetKey(KeyCode.A))
{
transform.Translate(-moveSpeed * Time.deltaTime, 0, 0);
}
if(Input.GetKey(KeyCode.D))
{
transform.Translate(moveSpeed * Time.deltaTime, 0, 0);
}
}
void Clamp()
{
transform.position = new Vector3(Mathf.Clamp(transform.position.x, leftBorder, rightBorder), Mathf.Clamp(transform.position.y, bottomBorder, topBorder), transform.position.z);
}
}
The Rigidbody2D performs the physics simulation and writes to the Transform. You’re bypassing that completely and driving the Transform directly completely stomping over what the physics is trying to do.
You: Hey, move the Rigidbody2D/Collider here which is likely overlapped with something
Physics: I’ll start moving out of overlap.
You: Hey, move the Rigidbody2D/Collider here which is likely overlapped with something
Physics: I’ll start moving out of overlap.
All physics movement should be done via the Rigidbody2D.
could u show me how to do rigidbody 2d movement?
i want the movement to feel like you’re completely in control and you don’t have to wait a little for it to start moving and you should be able to stop moving whenever u like without needing to wait to slow down
If it helps, the trick to making your Rigidbody player stop instantly is to make is to make the Rigidbody2D component’s velocity-as it says in the documentation-equal to input * speed. That way if there is no input, velocity is instantly zero. Also, don’t multiply input by the delta time, as that is what gives your player acceleration in the first place.