Search Unity

Stopping Movement After Collision

Discussion in 'Scripting' started by CoffeeConundrum, Jan 8, 2014.

  1. CoffeeConundrum

    CoffeeConundrum

    Joined:
    Dec 30, 2013
    Posts:
    46
    I've currently got a small room made up of four walls and a floor (all made out of cubes) and a cube sitting in the middle of this 'room'. I've got my camera being moved through the WASD keys with the lines of code below to move it in each direction.

    Code (csharp):
    1. if (Input.GetKey (KeyCode.W))
    2.             myCameraTransform.position += myCameraTransform.forward * speed * Time.deltaTime;
    3. if (Input.GetKey (KeyCode.A))
    4.     myCameraTransform.position -= myCameraTransform.right * speed * Time.deltaTime;
    5. if (Input.GetKey (KeyCode.S))
    6.     myCameraTransform.position -= myCameraTransform.forward * speed * Time.deltaTime;
    7. if (Input.GetKey (KeyCode.D))
    8.     myCameraTransform.position += myCameraTransform.right * speed * Time.deltaTime;
    I've got my collision detection working in a sepertate file which throws up messages in the console identifying which gameobject I've hit however I'm confused as to how I would manage to get this over to my file which has the above code in it, so that I can put the speed to zero to stop movement.

    Many thanks
     
  2. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    Simply don't assign a new position in case collision is detected. Best way in your case would be to get a reference to the other script taking care of collision and provide a public method returning a boolean value.

    However, this can grow quite large. One example:
    In case your cube hits a wall you will most likely have an "overlapping" area of colliders, one from the wall, one from the cube. Once overlapping your new public method, let's call it "Colliding()" will return true and thus the movement script won't assign a new position. So far so good. But what if you want to move in the opposite direction of the colliding wall?

    You'll need to take care of these cases. Or you can simply use the Character Controller which is part of Unity and takes care of all that stuff automatically.
     
  3. CoffeeConundrum

    CoffeeConundrum

    Joined:
    Dec 30, 2013
    Posts:
    46
    Thanks for the quick response but I should have been a bit more clearer, the camera is the moving object and the cube is in the room just for something to move around in the room and will later be used for my prototype.

    Many thanks for the help though and I've managed to resolve the issues