- Home /
Make my player who uses Character Controller to stop moving in one certain direction once it reaches the borders.
My player uses the Character Controller component to move and I wanted to stop its movement once it reaches the border.
For example, when my player reaches the very left side of the screen, I want the Character Controller to stop moving on the left side, but it can still keep going upwards, downwards, and to the right. My character uses this code:
charController.Move (((player.forward * joyDelta.z + player.right * joyDelta.x)) * player.speed * moveSpeed * Time.deltaTime);
When I try this, however:
if(GameObject.Find("Player").transform.position.z > -100 && GameObject.Find("Player").transform.position.z < 100)
{
charController.Move (((player.forward * joyDelta.z)) * player.speed * moveSpeed * Time.deltaTime);
}
if(GameObject.Find("Player").transform.position.x > -100 && GameObject.Find("Player").transform.position.x < 100)
{
charController.Move (((player.right * joyDelta.x)) * player.speed * moveSpeed * Time.deltaTime);
}
When it reaches the very left side of the screen, it will stop going through the left, but it will also stop going through the right. The same goes for the ups and downs.
Is there a way I can do this?
I wanted to only disable one direction. So if it hit the Northern Border, the controller will only disable the upwards movement, so it couldn't go upwards anymore, but it can still go downwards, eastwards, and westwards.
Thanks!
Answer by KilomanX · Jun 22, 2014 at 01:44 AM
in your code you only allow movement when the player is between -100 and 100 but you need to also let the player go back when he is outside, so if he is at the north border allow movement only if the movement is to the south, so we have: if(player is not at the north border OR movement is to south), we do this for south border too.
var movementZ=((player.forward * joyDelta.z)) * player.speed * moveSpeed * Time.deltaTime);
if((GameObject.Find("Player").transform.position.z > -100 || movementZ>0) && (GameObject.Find("Player").transform.position.z < 100 || movementZ<0))
{
charController.Move (movementZ);
}
(I made a variable for movement for better readability)
I think that can help you, do it for east-west too.