PacMan 3D Clone Movement
I am trying to make a PacMan like game, where the player has to finish the classic version of PacMan first before he can "evolve" and learn new abilities. For the first level I try to be as close to the original version as possible (although in 3D). The part where I am having problems now is to script the behavior that if PacMan moves between two walls and there is no way for him to go up or down, but the player presses the up/down key that PacMan does not stop (or rotates to the given axis) but moves to the next valid point and THEN moves in the direction the player has put in.
public class PacManMovement : MonoBehaviour { public float speed = 4.0f;
private Vector3 direction = Vector3.zero;
// Update is called once per frame
void Update()
{
CheckInput();
Move();
UpdateOrientation();
}
void CheckInput()
{
if (CanTurn(direction))
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
direction = Vector3.left;
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
direction = Vector3.right;
}
else if (Input.GetKeyDown(KeyCode.UpArrow))
{
direction = Vector3.forward;
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
direction = Vector3.back;
}
}
}
void Move()
{
if (Valid(direction))
{
transform.localPosition += (Vector3)(direction * speed) * Time.deltaTime;
}
}
void UpdateOrientation ()
{
if (Valid(direction))
{
if (direction == Vector3.left)
{
//transform.localScale = new Vector3(-100, 100, 100);
transform.localRotation = Quaternion.Euler(-90, 0, 90);
}
else if (direction == Vector3.right)
{
//transform.localScale = new Vector3(100, 100, 100);
transform.localRotation = Quaternion.Euler(-90, 0, -90);
}
else if (direction == Vector3.back)
{
//transform.localScale = new Vector3(100, 100, 100);
transform.localRotation = Quaternion.Euler(-90, 0, 0);
}
else if (direction == Vector3.forward)
{
//transform.localScale = new Vector3(100, 100, 100);
transform.localRotation = Quaternion.Euler(-90, 0, 180);
}
}
}
private bool Valid(Vector3 direction)
{
// Cast Line from 'next to Pac-Man' to 'Pac-Man'
Vector3 position = transform.position;
RaycastHit hit;
Ray ray = new Ray(position, direction);
if (Physics.Raycast(ray, out hit, 1.0f))
{
if (hit.collider != null && hit.collider.name != "pacman")
{
Debug.Log(hit.collider.name);
return false;
}
}
return true;
}
private bool CanTurn(Vector3 direction)
{
Vector3 position = transform.position;
RaycastHit longHit;
Ray ray = new Ray(position, direction);
if (Physics.Raycast(ray, out longHit))
{
if (longHit.distance > 1.0f && this.transform.position.x % 2 == 0 && this.transform.position.z % 2 == 0)
{
Debug.Log(longHit.collider.name);
return true;
}
}
return false;
}
}
Now the CanTurn class is the part that does not work as I intended. Maybe Im thinking wrong here, I am kind of new to scripting. But I thought making PacMan check if the position is able to be divided with 0 remainder it would work, but I am not sure where I am going wrong with this. Any help is appreciated! Also sorry for the weird formatting