- Home /
(2D) Have a player not move through a block
Assuming I have a player that's just a square with basic movement controls, and a box, how can I make it so that the player doesn't move through the box? Is there an easy way to do this?
I have a kinematic rigidbody2d and a box collider with isTrigger set to true on both of them and currently I am trying to take the coordinates of the box's vertices, and check which direction the player is colliding with the box, allowing me to disable that direction for the player. This doesn't seem to work however due to OnTriggerEnter2D only being able to pass a Collider and not a BoxCollider, stopping me from accessing BoxCollider.size.
Answer by swanne · Oct 12, 2021 at 09:31 AM
From your explanation I think that the collider parameter 'Is Trigger' is the fault. I use trigger type colliders to trigger an action when a player moves through it. A check point for example. I dont want the checkpoint to physically stop the player walking through it. I suggest making 'Is Trigger' false on both of your object colliders and testing.
That seems to not work. Maybe it is something with the way I do movement? Here is my code for it just in case:
void Update()
{
move();
}
private void move()
{
float moveX = Input.GetAxis("Horizontal");
float moveY = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveX, moveY, 0);
movement *= speed;
movement *= Time.deltaTime;
transform.Translate(movement);
}
Hey @HelloThere738
Try this for your movement script:
void Update()
{
move();
}
private void move()
{
float moveX = Input.GetAxis("Horizontal") * speed;
float moveY = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(moveX, moveY, 0);
transform.Translate(movement * Time.deltaTime);
}
Again, make sure that the collider component on both the player and the box are set 'Is Trigger = false'
Answer by glatteinfo · Oct 12, 2021 at 04:07 PM
Having Trigger enabled disables the "normal" collision. Just add a Second boxcollider and leave Trigger unchecked
Your answer
Follow this Question
Related Questions
How to add a 2D explosion force to players with physics based movement? 0 Answers
which is best method for 2d player movement 0 Answers
Trouble creating knockback when setting velocity on RigidBody2D 0 Answers
Rotate scene or camera with unity 2d physics 0 Answers
Unintended bounce on 2D platformer 1 Answer