3D场景中2D Sprite显示问题:敌人正对玩家前停止旋转问询
3D环境中2D Sprite垂直摄像机时消失的敌人旋转限制问题
我在3D环境中使用2D Sprite时遇到一个问题:当Sprite与摄像机垂直时会无法显示。我已经通过跟踪鼠标位置解决了玩家角色的该问题,代码如下:
if (lookAtMouseEnabled) { Lookatmouse(); } Vector3 mousePos = Input.mousePosition; //Debug.Log($"Mouse X: {mousePos.x}"); if (mousePos.x >= minXRotation && mousePos.x <= maxXRotation) { lookAtMouseEnabled = false; } else { lookAtMouseEnabled = true; }
但敌人角色无法采用同样的方法,我需要实现:判断玩家在敌人的左侧还是右侧,让敌人在正对玩家前20度时停止旋转,反向情况也一样。敌人当前的代码如下:
public Transform player; public float speed = 5.0f; public float rotationSpeed = 10.0f; public float chaseDistance = 2.0f; public float stoppingDistance = 1.0f; private Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { if (player == null) { GameObject playerObject = GameObject.FindGameObjectWithTag("Player"); if (playerObject != null) { player = playerObject.transform; } } if (player != null) { Vector3 direction = player.position - transform.position; float distance = direction.magnitude; if (distance > stoppingDistance) { //Rotation direction.Normalize(); Quaternion lookRotation = Quaternion.LookRotation(direction); rb.rotation = Quaternion.Slerp(rb.rotation, lookRotation, rotationSpeed * Time.fixedDeltaTime); //ChasePlayer Vector3 chasePosition = player.position - player.forward * chaseDistance; Vector3 newPosition = Vector3.MoveTowards(rb.position, chasePosition, speed * Time.fixedDeltaTime); rb.MovePosition(newPosition); // Determine if the player is on the left or right Vector3 enemyToPlayer = player.position - transform.position; Vector3 enemyRight = transform.right; float dotProduct = Vector3.Dot(enemyToPlayer, enemyRight); if (dotProduct < 0) { Debug.Log("Player is on the left."); } else { Debug.Log("Player is on the right."); } } } }
问题截图:

现寻求该问题的解决方案,恳请各位提供建议。
内容的提问来源于stack exchange,提问作者Spectral Visions
相关产品推荐
相关产品推荐

