I have followed the code exactly and I’m not sure why but I can’t get the ship to rotate on the correct axis.
I tried forward, up, down, back, left, and right. The rotation is always wrong.
When I tried moving the camera to a top-down perspective, it messed up the movement. Not really sure how to fix it. Some help would be appreciated.
Using Unity 2021.3
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed;
[SerializeField] private float maxVelocity;
[SerializeField] private float rotationSpeed;
private Camera mainCamera;
private Rigidbody rb;
private Vector3 moveDirection;
void Start()
{
mainCamera = Camera.main;
rb = GetComponent<Rigidbody>();
}
void Update()
{
MyInput();
KeepPlayerOnScreen();
RotateOnMovement();
}
private void FixedUpdate()
{
if (moveDirection == Vector3.zero)
{
return;
}
else
{
MovePlayer();
}
}
void MyInput()
{
try
{
CalculateMoveDiretion();
}
catch (NullReferenceException)
{
return;
}
}
void CalculateMoveDiretion()
{
if (Touchscreen.current.primaryTouch.press.isPressed)
{
Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(touchPosition);
moveDirection = worldPosition - transform.position; //Move to player's touch
moveDirection.z = 0f; //stop from moving up and down
moveDirection.Normalize(); //Just add a base fore, don't compound it
}
else
{
moveDirection = Vector3.zero;
}
}
void MovePlayer()
{
rb.AddForce(moveDirection * moveSpeed, ForceMode.Force);
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxVelocity);
}
private void KeepPlayerOnScreen()
{
Vector3 newPos = transform.position;
Vector3 viewPortPos = mainCamera.WorldToViewportPoint(transform.position);
if (viewPortPos.x > 1)
{
newPos.x = -newPos.x + 0.1f;
}
else if (viewPortPos.x < 0)
{
newPos.x = -newPos.x -0.1f;
}
else if (viewPortPos.y > 1)
{
newPos.y = -newPos.y + 0.1f;
}
else if (viewPortPos.y < 0)
{
newPos.y = -newPos.y - 0.1f;
}
transform.position = newPos;
}
void RotateOnMovement()
{
if (rb.velocity == Vector3.zero)
{
return;
}
else
{
Quaternion targetRotation = Quaternion.LookRotation(rb.velocity, Vector3.back);
transform.rotation = Quaternion.Lerp
(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
}