I probably should have asked this a few lectures ago but the movement of my spaceship is incredibly jittery. Is there anyway to fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] float forceMagnitude;
[SerializeField] float maxVelocity;
Camera mainCamera;
Rigidbody rigidBody;
Vector3 movementDirection;
// Start is called before the first frame update
void Start()
{
mainCamera = Camera.main;
rigidBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
movePlayer();
KeepOnScreen();
RotatePlayer();
}
private void FixedUpdate()
{
if (movementDirection == Vector3.zero)
{
return;
}
rigidBody.AddForce(movementDirection * forceMagnitude, ForceMode.Force);
// This stops the velocity from going above the maxVelocity
rigidBody.velocity = Vector3.ClampMagnitude(rigidBody.velocity, maxVelocity);
}
private void movePlayer()
{
if (Touchscreen.current.primaryTouch.press.isPressed)
{
Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(touchPosition);
movementDirection = worldPosition - transform.position;
movementDirection.z = 0;
movementDirection.Normalize();
}
else
{
movementDirection = Vector3.zero;
}
}
private void KeepOnScreen()
{
Vector3 newPosition = transform.position;
Vector3 viewportPosition = mainCamera.WorldToViewportPoint(transform.position);
if (viewportPosition.x < 0)
{
newPosition.x = -newPosition.x - 0.1f;
}
else if (viewportPosition.y < 0)
{
newPosition.y = -newPosition.y - 0.1f;
}
else if (viewportPosition.x > 1)
{
newPosition.x = -newPosition.x + 0.1f;
}
else if (viewportPosition.y > 1)
{
newPosition.y = -newPosition.y + 0.1f;
}
transform.position = newPosition;
}
private void RotatePlayer()
{
transform.rotation = Quaternion.LookRotation(rigidBody.velocity, Vector3.back);
}
}