- Home /
Gameobject doesn't move when hits wall
I have a GameObject that moves tile based (It moves 1 unity unit continuously when I press button) but when ıt hits a wall, ıt doesn't move anymore
As you see, When It hits a wall, ıt doesn't move any direction anymore. Actually I found the problem but I couldn't find how to solve. The main problem is when cube hits wall, the distance between nextPosition
and transform.position
never will be <0.0005f But Idk how to solve this.
Those are code that moves cube :
void MovePlayer()
{
rb.MovePosition(Vector3.MoveTowards(transform.position, nextPosition, speed * Time.deltaTime));
if (Input.GetKeyDown(KeyCode.W))
{
direction = Vector3.forward;
}
if (Input.GetKeyDown(KeyCode.S))
{
direction = Vector3.back;
}
if (Input.GetKeyDown(KeyCode.A))
{
direction = Vector3.left;
}
if (Input.GetKeyDown(KeyCode.D))
{
direction = Vector3.right;
}
if (Vector3.Distance(transform.position, nextPosition) < 0.0005f)
{
nextPosition = transform.position + direction;
}
}
Answer by Rosalinds · Jul 07, 2021 at 12:31 PM
The first is that if your if
statement is never being reached (groundInfo.Collider == true)
then of course your enemy just keeps walking in the direction they're going and never turns around. I highly suspect this is the case.
Answer by Astrydax · Jul 07, 2021 at 06:48 AM
Another approach you can use that is commonly used in game development is to actually move the game object instead of using "next location". Move the object, do the tests, then move it back in the same frame. All this will happen before the frame renders and will appear to the player that the object never moved.