[英]Unity C# - How to check if random moving gameobject is within boundaries
我有一个随机移动的游戏对象在带有附加代码的场景中移动。 问题在于,尽管存在带有刚体的边界对撞机,但有时它会直接穿过它们并落下。
我如何限制它一旦撞到那些对撞机它会旋转 189 圈并继续随机移动?
地形宽度为 50f,地形高度也为 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);
}
您可以使用OnCollisionEnter
在单位撞到其他对撞机时触发旋转。
这样的事情必须这样做:
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag(or name) = "a tag or name"){
//Do Stuff here
}
}
这是详细的文档: https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
另一种解决方法是使用NavMesh
。 它将使动作基于UnityEngine.AI
并且非常流畅,但您需要一个全新的脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.