- Home /
Make a sprite stop after a collision.
I am a first-day unity user and have made a program in which a small robot moves around randomly on a plane. At the end of the plane are walls and I want the robot not to be able to go through them. What can I do to achieve this? Here is the script for the robot.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RobotMovement : MonoBehaviour { private Vector3 movement; private Rigidbody rb; private int Health; private float xvel; private float zvel; private float xacc; private float zacc; void Start() { xvel = 0F; zvel = 0F; xacc = 0F; zacc = 0F; }
void Update()
{
transform.Translate(xvel,0,zvel);
if (xvel > 0.1) {xvel = .1F;}
if (xvel < -0.1) {xvel = .1F;}
if (zvel > 0.1) {zvel = .1F;}
if (zvel < -0.1) {zvel = .1F;}
xacc = Random.Range(-0.01F,0.01F);
xvel = xvel + xacc;
zacc = Random.Range(-0.01F,0.01F);
zvel = zvel + zacc;
}
void OnCollisionEnter(Collision Collision)
{
if (xacc > 0) {xacc = -1F;}
if (xacc < 0) {xacc = 1F;}
if (zacc > 0) {xacc = -1F;}
if (zacc < 0) {xacc = 1F;}
}
}
Thank you so much!
Do both the walls and your robot have some sort of Collider? When you say it goes through the wall, Is it either going through because the wall doesn't have collision, or is it just hitting the wall and attempting to continue moving?.
It all depends on which of these is the case. If you're making it act like a Roomba vacuum, you could do something like this.
void OnCollisionEnter(Collision collision) //$$anonymous$$ake sure second collision is lowercase.
{
if(collision.GameObject.Tag == "Wall" //Need to confirm this is correct, as im used to triggers
{
//Add a bool to check if robot can move to above part of script
can$$anonymous$$ove = false;
//Add code to rotate robot 90degrees (or whatever you want)
cann$$anonymous$$ove = true;
}
}
Or you can just use the Can$$anonymous$$ove = false; to stop it. I'm not sure if this is the sort of thing you're after, but I hope it helps with something until someone more experienced can post.
Answer by Lightning_A · Jun 20, 2019 at 06:42 PM
All you have to do is put a collider component on each of the walls. Assuming the walls are rectangular, you probably want a BoxCollider (for 3D games) or a BoxCollider2D (for 2D games). Just make sure isTrigger is set to false (isTrigger means that the collider is used to detect collisions, but the game object isn't actually solid). Also, be sure that the size of the collider is the same as the scale of the walls (so that the entire wall is solid, not just part of it; the collider is what makes a game object "solid").
Here's the documentation: https://docs.unity3d.com/ScriptReference/Collider.html