My goal is to make player not able to move in the direction of wall if he will collide with him on next step(for example if player presses “A”, and with this press he will collide with the wall, nothing will happend, but he will be able to move forward with “W” if next step is not colliding with the wall and so on.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public bool smoothTransition = false;
public float transitionSpeed = 10f;
public float transitionRotationSpeed = 500f;
Vector3 targetGridPos;
Vector3 prevTargetGridPos;
Vector3 targetRotation;
private void Start()
{
targetGridPos = Vector3Int.RoundToInt(transform.position);
Collider collider = gameObject.AddComponent<BoxCollider>();
collider.isTrigger = false;
}
private void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
if (true) // here is an error?
{
prevTargetGridPos = targetGridPos;
Vector3 targetPosition = targetGridPos;
if (targetRotation.y > 270f && targetRotation.y < 361f) targetRotation.y = 0f;
if (targetRotation.y < 0f) targetRotation.y = 270f;
if (!smoothTransition)
{
transform.position = targetPosition;
transform.rotation = Quaternion.Euler(targetRotation);
}
else
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * transitionSpeed);
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(targetRotation), Time.deltaTime * transitionRotationSpeed);
}
// Check for collisions with walls
Collider[] hitColliders = Physics.OverlapSphere(transform.position, 0.4f);
foreach (Collider hitCollider in hitColliders)
{
Debug.Log("Collided with " + hitCollider.gameObject.name);
if (hitCollider.gameObject.CompareTag("Wall"))
{
targetGridPos = prevTargetGridPos; // move the player back to their previous position
break;
}
}
}
else
{
targetGridPos = prevTargetGridPos;
}
}
void OnCollisionEnter(Collision collision)
{
// Check if the collision is with a wall
if (collision.gameObject.tag == "Wall")
{
// Move the player back to their previous position
targetGridPos = prevTargetGridPos;
}
}
public void RotateLeft() { if (AtRest) targetRotation -= Vector3.up * 90f; }
public void RotateRight() { if (AtRest) targetRotation += Vector3.up * 90f; }
public void MoveForward() { if (AtRest) targetGridPos += 2 * transform.forward; }
public void MoveBackward() { if (AtRest) targetGridPos -= 2 * transform.forward; }
public void MoveLeft() { if (AtRest) targetGridPos -= transform.right; }
public void MoveRight() { if (AtRest) targetGridPos += transform.right; }
bool AtRest
{
get
{
if ((Vector3.Distance(transform.position, targetGridPos) < 0.05f) &&
(Vector3.Distance(transform.eulerAngles, targetRotation) < 0.05f))
return true;
else
return false;
}
}
}