I have an image of the ground. I character walks on the ground. I want to confine the character sprite inside the ground image. When the character reaches the edge of the ground image, I want them to go no further.
I know I could put rigid bodies surrounding the image of the ground. However, is there a way to simply calculate the location of the character on the ground image and stop it when the width or height of the image is reached?
I hope that makes sense.
Try this: (C#)
void Update()
{
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, -10f, 5f); //This locks the player’s left and right movement.
//pos.y = Mathf.Clamp(pos.y, 0f, 0f); This will lock the player’s up and down movement.
transform.position = pos;
}
It doesn’t work on individual boundary objects but it does work to set map movement restrictions. The player will not be able to move past the points you set.
(The -10f is how far the player can move to the left and the 5f is how far the player can move to the right. Change them however you want)
Let me know if it works!
Thank you for responding. Is there a way to find the size of the ground image through code and then set the clamp to the width and height of the image?
Possibly, I’d have to look into it. Is it a randomly generated ground or something like that? If not I usually just smack my character against the wall and adjust it until the boundary is where I want it.
If the ground moves or something like that you can make two integers (int leftSide, int rightSide) then adjust them in code so the boundaries move with the map:
int leftSide = -10;
int rightSide = 5;
void Update()
{
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, leftSide, rightSide);
transform.position = pos;
}
It is a fixed image, but another level may be a different size. I would love to know how to pass the width/height info to a variable then clamp it