- Home /
How can I make my character after hitting a wall?
I am super new to Unity (first day) and am had coded this program where a little robot moves around randomly . It is on a plane with walls on the sides(cubes).
I want it to not be able to go through the walls. Here is the robot's script:
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! I have not been able to find an answer on the internet.
Answer by Freesmith · Jun 20, 2019 at 06:00 PM
hi, i would suggest a standard solution using unity physics. Having a rigid body and a collider on your robot game object and a collider on the walls and floor plane would be enough. And be sure to use Rigidbody.MovePosition to move a Rigidbody.