敌人gameObject没有移动
本文关键字:移动 gameObject 敌人 | 更新日期: 2023-09-27 18:14:38
我遇到了一个关于敌人执行的问题。首先,我遵循本教程。我有一个带有盒子碰撞器的敌人的游戏对象,基本上就是我所需要的。
下面是我的脚本:using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
[SerializeField]
private float rotationSpeed = 180; // In degrees per second
[SerializeField]
private float movementSpeed = 1f; // In units per second
[SerializeField]
private float meshRadius = 1f; // In units
private IEnumerator turnTowardsPlayerCoroutine;
private IEnumerator moveTowardsPlayerCoroutine;
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.tag == "Player")
{
float playerDistance = Vector3.Distance(collider.transform.position, transform.position);
// Ignore trigger events from the inner colliders
if (playerDistance >= 2f * meshRadius)
{
turnTowardsPlayerCoroutine = TurnTowardsPlayer(collider.transform);
moveTowardsPlayerCoroutine = MoveTowardsPlayer(collider.transform);
StartCoroutine(turnTowardsPlayerCoroutine);
StartCoroutine(moveTowardsPlayerCoroutine);
}
}
}
void OnTriggerExit(Collider collider)
{
if (collider.tag == "Player")
{
float playerDistance = Vector3.Distance(collider.transform.position, transform.position);
// Ignore trigger events from the inner colliders
if (playerDistance >= 2f * meshRadius)
{
StopCoroutine(turnTowardsPlayerCoroutine);
StopCoroutine(moveTowardsPlayerCoroutine);
}
}
}
private IEnumerator TurnTowardsPlayer(Transform player)
{
while (true)
{
Quaternion targetRotation = Quaternion.LookRotation(player.position - transform.position, Vector3.up);
targetRotation.x = 0f;
targetRotation.z = 0f;
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
yield return 0;
}
}
private IEnumerator MoveTowardsPlayer(Transform player)
{
while (true)
{
Vector3 playerDirection = transform.position - player.position;
playerDirection.y = 0;
playerDirection = playerDirection.normalized;
Vector3 deltaMovement = playerDirection * movementSpeed * Time.deltaTime;
int layermask = LayerMask.GetMask("Environment");
Vector3 movingTowards = transform.position - playerDirection*meshRadius + (new Vector3(0f, 0.1f, 0f));
if (Physics.Raycast(movingTowards, Vector3.down, 0.25f, layermask))
{
transform.position -= deltaMovement;
}
yield return 0;
}
}
}
结果是,当我进入敌人必须攻击我的区域时,敌人向我旋转,但他没有移动。是我忘了什么还是出了什么问题?
我已经看了几次那个教程,脚本是正确的。似乎缺少的是这一层。确保"Environment"层存在,并将其分配给环境对象。
将"环境"图层添加到必要对象的最简单方法是选择层次结构中应该在"环境"图层中的每个对象,然后在检查器中更改图层。
如果物理光线投射不成功,这可能意味着以下事情之一:
-layermask设置错误(它忽略了特定的分层对象,它没有击中任何东西)
你把它送错方向了
-射击距离太小,问题是,在你正在观看的教程中,它可能适用于这个值,但你可能有不同的缩放你的关卡。试着把它设置成更大的值(100,1000)