I want my character to stop everytime I hit the edge of the screen/canvas, so I added some rectangle at the end of each border(with a 2d collider), so my character will collide with it and stop moving in that direction, but the thing is that if, for example, I hit the left rectangle and I still press A to move left, my character strarts 'shaking'. I tried to solve that by setting the speed of it to 0 when it hits the certain rectangle, but then I cant move at all in any directions after I get to the edge.
public class CharacterMovement : MonoBehaviour {
public float speed = 5f;
void Start() {
}
void Update() {
if (Input.GetKey(KeyCode.W))
{
transform.Translate(0, speed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(0, -speed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "offscreen")
{
speed = 0f;
}else
{
speed = 5f;
}
}
}