Question by
haxorbird · Nov 24, 2020 at 01:54 PM ·
instantiatepositiongrid based game
How to check for the previous position of the player?
I have a player cube with grid movement. When I press any of wasd keys or the screen is swiped, it moves in a specific direction:
if (Input.GetKeyDown(KeyCode.W) && !isMoving || SwipeDetector.SwipeUp && !isMoving)
{
if (CanMove(Vector3.forward))
{
//Player moves one grid forward
StartCoroutine(MovePlayer(Vector3.forward));
}
}if (Input.GetKeyDown(KeyCode.A) && !isMoving || SwipeDetector.SwipeLeft && !isMoving)
{
if (CanMove(Vector3.left))
{
//Player moves one grid to the left
StartCoroutine(MovePlayer(Vector3.left));
}
}if (Input.GetKeyDown(KeyCode.S) && !isMoving || SwipeDetector.SwipeDown && !isMoving)
{
if (CanMove(Vector3.back))
{
//Player moves one grid backwards
StartCoroutine(MovePlayer(Vector3.back));
}
}if (Input.GetKeyDown(KeyCode.D) && !isMoving || SwipeDetector.SwipeRight && !isMoving)
{
if (CanMove(Vector3.right))
{
//Player moves one grid to the right
StartCoroutine(MovePlayer(Vector3.right));
}
}
CanMove is a bool function which checks if a raycast is hitting an object in a specific side. And this is MovePlayer:
public IEnumerator MovePlayer(Vector3 direction)
{
isMoving = true;
float elapsedTime = 0f;
origPos = transform.position;
targetPos = origPos + direction;
while (elapsedTime < timeToMove)
{
transform.position = Vector3.Lerp(origPos, targetPos, elapsedTime / timeToMove);
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
I have two variables, currentPos and previousPos. currentPos is equal to player's transform.position. I want the previousPos to be equal to the previous grid position after the player has stopped on the new grid. Please Help.
Comment