Skip to main content
Bumped by Community user
edited tags
Link
Source Link

How to restrict player movement without jitters

I am currently making top-down space shooter and would like to hear some suggestions on how to restrict player movement without causing jitters. Everything works fine except one thing: the player (spaceship) jitters back and forth when trying to move beyond the game bounds. Here is a short video to show you what I mean: https://drive.google.com/file/d/1ZsBHnSakQYh0J5srJC_KUbB00OSSQFA9/view?usp=sharing And here is a script:

using System.Collections.Generic;
using UnityEngine;

public class Starship : MonoBehaviour
{
    private float moveX, moveY;
    private float boundsY = 450f, boundsX = 850f;
    
    [SerializeField]
    private float moveSpeed;
    
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        moveX = Input.GetAxis("Horizontal");
        moveY = Input.GetAxis("Vertical");
        Vector3 currentPosition = transform.localPosition;
        transform.localPosition += new Vector3(moveX, moveY) * moveSpeed * Time.deltaTime;
        if (currentPosition.y < -boundsY)
            transform.localPosition = new Vector3(currentPosition.x, -boundsY);
        else if (currentPosition.y > boundsY)
            transform.localPosition = new Vector3(currentPosition.x, boundsY);
        else if (currentPosition.x < -boundsX)
            transform.localPosition = new Vector3(-boundsX, currentPosition.y);
        else if (currentPosition.x > boundsX)
            transform.localPosition = new Vector3(boundsX, currentPosition.y);
    }
}