Question by
unity_aA5ExDZRCeJt-A · May 11, 2020 at 08:23 AM ·
movementcollider3ddetection
Unity C# - How to check if random moving gameobject is within boundaries
Hi I have a random moving gameobject moving in the scene with the attached code. The issue is that although there are boundary colliders with a rigid body, sometimes it passes right through them and falls.
How can I limit it that once it bumps into those colliders it does a 189 rotation and continues moving randomly?
The terrain width is 50f, the terrain Height is also 50f.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTrainingMovement : MonoBehaviour {
public float speed;
private float randomizedSpeed = 0.0f;
private float nextActionTime = -1.0f;
private Vector3 targetPosition;
private Vector3 moveVector;
private void FixedUpdate() {
if(speed > 0.0f) {
Move2();
//Move();
}
}
private void Move2() {
if(Time.fixedTime >= nextActionTime) {
// Get a threshold time
nextActionTime = UnityEngine.Random.Range(50.0f, 200.0f);
// Pick a random target position
targetPosition = TrainingArea.ChooseRandomPosition(transform.parent.position, 0f, 270f, 2f, 10f);
// Rotate towards the target position
transform.rotation = Quaternion.LookRotation(targetPosition - transform.position, Vector3.up);
float timeToGetThere = Vector3.Distance(transform.position, targetPosition) / randomizedSpeed;
nextActionTime = Time.fixedTime + timeToGetThere;
// Get a movement vector
moveVector = speed * transform.forward;
//moveVector = speed * new Vector3(1.0f, 0.0f, 0.0f);
}
else {
// Check -X boundary
if(transform.position.x - 1.0f <= transform.parent.gameObject.transform.position.x) {
transform.position = transform.position + new Vector3(1.0f, 0.0f, 0.0f);
moveVector.x *= -1.0f;
}
// Check +X boundary
if(transform.position.x + 1.0f >= transform.parent.gameObject.transform.position.x + TrainingArea.terrainWidth) {
transform.position = transform.position + new Vector3(-1.0f, 0.0f, 0.0f);
moveVector.x *= -1.0f;
}
// Check -Z boundary
if(transform.position.z - 1.0f <= transform.parent.gameObject.transform.position.z) {
transform.position = transform.position + new Vector3(0.0f, 0.0f, 1.0f);
moveVector.z *= -1.0f;
}
// Check +Z boundary
if(transform.position.z + 1.0f >= transform.parent.gameObject.transform.position.z + TrainingArea.terrainHeight) {
transform.position = transform.position + new Vector3(0.0f, 0.0f, -1.0f);
moveVector.z *= -1.0f;
}
// Move
transform.position = transform.position + moveVector * Time.fixedDeltaTime;
// Update nextActionTime
nextActionTime--;
}
}
}
public static Vector3 RandomPositionOnTerrain(Vector3 origin) {
//Range(30.0f, terrainWidth - 30.0f);
float randomX = origin.x + UnityEngine.Random.Range(20.0f, terrainWidth);
float randomZ = origin.z + UnityEngine.Random.Range(20.0f, terrainHeight);
return new Vector3(randomX, 30.0f, randomZ);
}
Comment