- 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?
Thanks! :)
This question isn't "unanswered". First it has an answer and second it's the easiest way to make a CharacterController to stop moving in a certain direction. You don't need any code since the CC simply collides with your boundary colliders. Just place them at your desired positions.
You provided almost no information about your type of game or how the character is supposed to move. Does the camera move / scroll in any direction? Is it a top-down game? Is it something else?
Answer by Nick4 · Jun 15, 2014 at 03:36 AM
Create an empty game object and attach a collider to it then place it wherever your border is. Your player won't be able to move past the object.
Is there a way where if it touches the collider, it will make the character controller stop moving on one direction of the screen? Thanks! :)
Of course, use OnCollisionEnter method to detect the click then clamp the position of the controller. Good luck.
I tried clamping the position of the player but the controll still tries to move the player, so it's kind of stuttering since I've clamped it yet it's forcing to go through it.
And, how do you exactly clamp the controller?
Thanks for helping :)
Let's say you want to clamp the y axis between 1 and 5.
Vector3 pos = transform.position;
transform.position = new Vector3(pos.x, $$anonymous$$athf.Clamp(Time.time, 1, 5), pos.z);
Alternatively, you can instantiate a new object with a collider as soon as you detect the click.
I wanted the Controller to stop completely from moving my player though. This just prevents my player from going past 5, but the controller will still try to force the player to go through it.