Hi there,
I am following Mobile game course and my Asteroid Avoider game seems far from finishing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float forceMagnitude;
[SerializeField] private float maxVelocity;
[SerializeField] private float rotationSpeed;
private Rigidbody rb;
private Camera mainCamera;
private Vector3 movementDirection;
void Start()
{
rb = GetComponent<Rigidbody>();
mainCamera = Camera.main;
}
void Update()
{
ProcessInput();
KeepPlayerOnScreen();
RotateToFaceVelocity();
}
void FixedUpdate()
{
if (movementDirection == Vector3.zero) { return; }
rb.AddForce(movementDirection * forceMagnitude * Time.deltaTime, ForceMode.Force);
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxVelocity);
}
private void ProcessInput()
{
if (Touchscreen.current.primaryTouch.press.isPressed)
{
Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
// Log the touch position before converting it to world position
Debug.Log("Touch Position: " + touchPosition);
// Check for infinite values in the touch position
if (float.IsInfinity(touchPosition.x) || float.IsInfinity(touchPosition.y))
{
Debug.Log("Touch Position contains Infinity");
return;
}
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(touchPosition);
// Log the world position after the conversion
Debug.Log("World Position: " + worldPosition);
movementDirection = transform.position - worldPosition;
movementDirection.z = 0f;
movementDirection.Normalize();
}
else
{
movementDirection = Vector3.zero;
}
}
private void KeepPlayerOnScreen()
{
Vector3 newPosition = transform.position;
Vector3 viewportPosition = mainCamera.WorldToViewportPoint(transform.position);
bool positionChanged = false;
Debug.Log("Initial viewport position: " + viewportPosition);
if (viewportPosition.x > 1)
{
viewportPosition.x = 0;
positionChanged = true;
}
else if (viewportPosition.x < 0)
{
viewportPosition.x = 1;
positionChanged = true;
}
if (viewportPosition.y > 1)
{
viewportPosition.y = 0;
positionChanged = true;
}
else if (viewportPosition.y < 0)
{
viewportPosition.y = 1;
positionChanged = true;
}
Debug.Log("Updated viewport position: " + viewportPosition);
if (positionChanged)
{
newPosition = mainCamera.ViewportToWorldPoint(viewportPosition);
newPosition.z = transform.position.z;
transform.position = newPosition;
Debug.Log("Updated world position: " + newPosition);
}
}
private void RotateToFaceVelocity()
{
if (rb.velocity == Vector3.zero) { return; }
Quaternion targetRotation = Quaternion.LookRotation(rb.velocity, Vector3.back);
transform.rotation = Quaternion.Lerp(
transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
Do you have any idea about what i am missing here?