I have two objects: a player and a wall.
The player is passing through the long side of the wall but it collided with the short side of the wall.
I want the player to collide with whole wall.
Here is the code:
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityI have two objects: a player and a wall.
The player is passing through the long side of the wall but it collided with the short side of the wall.
I want the player to collide with whole wall.
Here is the code:
As I explained here there are 2 ways of moving objects:
You chose method 1, which is good method (I use it to move units in my RTS game). However you ran into the problem.
Your problem is this:
Choosing to change transform position directly, you are basically telling unity - no matter what happens move this object a little every frame. Computer does exactly that - no matter what walls , colliders are in the way computer tries to move your transform. At the same time you set up collider system thus asking physics engine to take care of collisions. So now two systems are fighting each other - physics system with colliders tries to stop objects overlapping, and your Update() function heroically tries to change transform position no matter what. Result - buggy unpredictable behavior.
The 2 solutions:
First one.
Since you move object directly without physics, also stop it directly without using physics. To do that in your player object check the box isTrigger (might need to do it on the wall object also). What it does, is tells physics system that this player object is not to be affected by collisions, but it will inform you if such collision occurred. Then set the tag of wall object to something like "wall". Then, in your player script use OnTriggerEnter() to find out if you hit the wall.
This would be simplified example of code:
bool amMoving;
public void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "wall" && amMoving == true)
{
amMoving == false;
}
}
void FixedUpdate()
{
if (amMoving == true)
{
// here write your code to move transform little by little
}
}
Second solution - do not move player object every frame, instead give rigidbody of player object velocity or force. And physics system will stop it when collision occurs.
I would try changing the type of collision detection of the rigidBodies. They might be moving to fast and be "tunneling" through objects. unity docs
You can read more about different types of collision detection here