[2D] Make player push object
Hello to everyone!
I am working on a top down 2D game and I need your help with pushing an object.
My player, which is a monster, should push a box when it collides with it. I tried several solutions, only one works for me but it works not smooth.
Here is my code for the box:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
this.direction = other.GetComponent<Monster> ().direction;
transform.Translate (other.GetComponent<Monster>().direction * other.GetComponent<Monster>().speed * Time.deltaTime);
}
}
The player has the Monster.cs script on it an has a given direction, saved in direction.
What am I doing wrong? Or is there a better solution to push an object in a top down 2D game?
Thanks in advance!
Answer by AMU4u · Mar 02, 2017 at 04:53 PM
Make a specific collider for those objects or maybe ALL objects (eh?) that is only for pushing/physics.
Right now if you have trigger colliders , they won't push each other around. Add another one, go into edit>project settings>physics and add a layer that only touches itself. Put colliders on your objects that will be pushed and add the collider to the physics layer.
For this to work, the object to be pushed needs a rigidbody attached to it.
EDIT - For people using raycasting to triggers with no rigidbodies for their colliders/collisions etc, simply go into edit>Project Settings>Physics and check the box that says, "Queries Hit Triggers". You will raycast to triggers and move them as if rigid bodies were involved.
Thank you!
I did the following: - deleted the script (with the code above) from the box; because it is not necessary anymore? - created a new layer named "pushable", it touches only itself - made a collider (no material) for the player and also a collider (no material) for the box - then I gave the player and box the same layer
But it doesn't work, I think i misunderstood something?
I should have asked, how is the character movement handled?
I checked your answer again and unchecked the arrow at "is trigger". Now it works quite nice! Thank you.
Your answer
Follow this Question
Related Questions
[2D] Slide object after collision 2 Answers
Objects are sliding when one is placed on top of the other in a top down game 0 Answers
Player can only jump once!? 0 Answers
Unity 2D: Interpolate object collision stuck 1 Answer
2D Android Game Rapid Jumping Problem,Unity 2018.2.9f1 Android 2d Speed Jumping 0 Answers