Search Unity

Keep Objects From Moving Into Occupied Spaces

Discussion in 'Physics' started by Zellybeanz, Jun 25, 2019.

  1. Zellybeanz

    Zellybeanz

    Joined:
    Jun 10, 2019
    Posts:
    7
    My game board is basically a plane of 1x1 tiles, the game pieces are 4 1x1x1 cubes stuck together in different configurations depending on which prefab. In all cases, there is one parent cube with the script attached to it and the 3 children have transforms and box colliders. I've got my script to the point where I can use keyboard to move a piece along x and z axis or rotate it by 90degree intervals (using the parent cube as a pivot point). Right now you have to hit the button each time you want to move it by one tile, but it would be nice if I could make it more Tetrislike later, where you could hold down button to keep moving.

    Once player is satisfied with placement, they hit spacebar to remove the movement script from that piece and respawn a new piece. I have a variable "placed" that changes to true and I've also tried changing the tag.

    With the new piece, if it's just falling and lands on another piece, it stops because of gravity on the rigidbodies. But as I use the movement script to move that new piece around, I'm finding that it lets me move it into the old piece(s). Sometimes that makes the placed piece bounce into the air, sometimes it just occupies the same space so it looks like one object. Neither of these behaviors are ok. Ideally it shouldn't even let me move that direction if it would cause an overlap. What is the code to do that? Keep in mind the parts of the piece are always colliding with each other. So it needs to check only if one of those parts would punch through the colliders on any part of another piece and stop it from doing that.
     
  2. Maeslezo

    Maeslezo

    Joined:
    Jun 16, 2015
    Posts:
    331
    If you are moving a rigidbody by its transform (for example, by transform.Translate), you can have this kind of problems. You should move it with rigidbody methods (like AddForce, or Velocity, MovePosition, etc).

    However, if you need a quick fix, you can try setting isKinematic = true when a piece is placed (when you set your variable placed to true)