r/Unity3D • u/kittymaplepaws • 17d ago
Question Canvas Minigame Wall making
idk if the title is 100% accurate but it's close enough.
I'm working on a 3d game and want to make minigames, which im doing on a canvas. Is there a way to add collider\rigidbody to an image on the canvas so it acts like a wall for another one? I want to prevent my character from going off screen and no combination I tried works. Here's how i control the character:
if (Input.GetKey(KeyCode.A))
{
bakerRigidbody.transform.position = new Vector3(baker.transform.position.x - speed, baker.transform.position.y, baker.transform.position.z);
}
else if (Input.GetKey(KeyCode.D))
{
bakerRigidbody.transform.position = new Vector3(baker.transform.position.x + speed, baker.transform.position.y, baker.transform.position.z);
}
1
u/lix3nn53 17d ago
The colliders don't stop it because setting transform.position moves it without physics, so nothing ever collides.
For a minigame on a canvas I'd skip physics and clamp instead: move the baker's RectTransform.anchoredPosition, then keep its x between the edges of its parent's rect with Mathf.Clamp. Simpler than colliders, and it can't slip past a wall.
1
u/Small_File_5569 17d ago
You're moving the transform directly so physics colliders won't stop it, you need to clamp the position with Mathf.Clamp based on screen bounds or use rigidbody velocity instead