I’m wondering how I can prevent objects from moving through each other. I currently have one object that I’m able to move around on the map. At the moment the moveable object goes on-top or below (depending on the layer priority) the stationary objects.
I’ve added a box collider 2d to all of the objects (the moveable and stationary ones). I’m guessing I need to script something with Collider.OnCollisionEnter(Collision) but I don’t know where to start. I’ve visited the help page about that specific function but I didn’t get any wiser. Hopefully someone is able to drop some hints where I should begin with.
how are you moving your object ? You dont need any script for this “preventing objects from moving through each other”, if both of them have collider2D (moved object should have rigidbody2D). I think, you are using for moving something with transform. and just put one gameobject in other. Try to use rigidbody2D.velosity or .addForce for moving.
I am using transform.Translate (Vector2.up * 5f * Time.deltaTime); for the movement. I’m not using a rigidbody because I thought that was only for physics such as pushing things back but I don’t need any of that.
I’ve used gravity 0 and checked fixed angle. For some reason it “shakes” when I push against the objects, is there any way to fix that? It’s basically not completely stationary at the moment.
playing with parametrs is good way to learn unity But later you should change transform. moving to physic moving with rigidbody2D (if you need physic). With transform. you will just replace the objects position in the world. So you can move through gameobjects like walls. In fixed timeintervals the physic engine is trying to correct the objects position.
You can go other way too. So you can use transform. moving without physic, but then you will need make own scripts for objects colliding.
And in your game you can use both methods. Physic for player movement, transform for backgrounds or camera.
That sounds pretty complicated, which is the easiest for a beginner you think? I don’t have a clue on where to start at the moment. Is there a way to just disable the correction of an objects position?
I am new to unity but not to the idea of game design and development.
I would advise not setting ridged bodies/physics etc to things that will be out of range, say you have a play area but you have buildings outside this area to make the scene look bigger or if you have a platform that the player will never reach etc, having no physics attached to these items will help with the overall performance of the end product, if you set physics to everything then this could have implications on performance for larger scenes as the computer has to process extra stuff when it is not needed.