Random Movement collision bug

Hey guys I tried getting a fix for this earlier but I can’t get it working. What I want is the object to move at random speeds. This is fine and working and changes direction at random intervals. Basically what I want is for the object to collide with something and change its direction (IMPORTANT: I have a fence around my plane to stop people exiting the map, when the object collides with this, I want the object to in effect “bounce” off it). At the moment it does this but sometimes it bugs and goes flying through the fence (I guess it changes it volicity that way twice in a row and glitches. Here is the code:

var chicken : Transform; 
var vel : Vector3;
var Direction : float = 3;
var curTime : float = 0;
function Start()
{
  SetVel();
}
function SetVel()
{
  if (Random.value > .5) {
    vel.x = 10 * 10 * Random.value;
  }
  else {
    vel.x = -10 * 10 * Random.value;
  }
  if (Random.value > .5) {
    vel.z = 10 * 10 * Random.value;
  }
  else {
    vel.z = -10 * 10 * Random.value;
  }
}

function Update()
    {
     if (curTime < Direction) {
     curTime += 1 * Time.deltaTime;
  }

  else {
        SetVel();
           if (Random.value > .5) {
           Direction += Random.value;
}

  else {
      Direction -= Random.value;
  }
        if (Direction < 1) {
        Direction = 1 + Random.value;
    }
    curTime = 0;
  }
}


function FixedUpdate()
    {
  chicken.rigidbody.velocity = vel;
}


function OnTriggerEnter(c:Collider)
{
SetVel();
  }

Anyone know a good way of going about this? Thanks in advance! :slight_smile:

Jim

If the fences form a square aligned to the axes x and z, the easiest solution is to give different names to them, like “top”, “bottom”, “left” and “right”, and in OnTriggerEnter revert only the z or x velocity, like this:

function OnTriggerEnter(fence: Collider){
  switch (fence.name){
    case "left":
    case "right":
      vel.x = -vel.x;
      break;
    case "top":
    case "bottom":
      vel.z = -vel.z;
      break;
  }
}

Your collision logic doesn’t account for a bounce. When you enter the trigger you are just randomizing the direction and that direction could be any direction, including one that goes through the object (and since you are using OnTriggerEnter and not OnTriggerStay it will only be called one time when the object first enters). Have you considered turning IsTrigger OFF and instead using OnCollision? If you do that then you wouldn’t need to worry about the change in direction from bounce, it would be accounted for automagically, and all you would need to worry about are the random changes in direction that you desire. Also its worth noting that

  if (Random.value > .5) {
    vel.x = 10 * 10 * Random.value;
  }
  else {
    vel.x = -10 * 10 * Random.value;
  }

Could be simplified to a single line, and will still give you the functionality you desire.

  vel.x = multiplier * (Random.value-.5);

Use a character controller instead!