C# 我的精灵只有在';他离运动员很近
我在我的2D Unity游戏中制造了一个敌人,我试图在精灵朝向相反方向时翻转它,事实是,只有当玩家非常接近敌人时,精灵才会翻转。这是我的代码:C# 我的精灵只有在';他离运动员很近,c#,unity3d,C#,Unity3d,我在我的2D Unity游戏中制造了一个敌人,我试图在精灵朝向相反方向时翻转它,事实是,只有当玩家非常接近敌人时,精灵才会翻转。这是我的代码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMovement : MonoBehaviour { public float moveSpeed; private PlayerMoveme
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
public float moveSpeed;
private PlayerMovement player;
public float playerRange;
public LayerMask playerLayer;
public bool playerinRange;
private bool Right = false;
private void Start()
{
player = FindObjectOfType<PlayerMovement>();
}
private void Update()
{
playerinRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerinRange)
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime);
}
Flip();
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawSphere(transform.position, playerRange);
}
private void Flip()
{
if (transform.position.x > 0 && !Right || transform.position.x < 0 && Right)
{
Right = !Right;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
公共阶层的复仇运动:单一行为
{
公共交通速度;
私人玩家移动玩家;
公众游艺;
公共层媒体播放器层;
公共场所;
私有布尔右=假;
私有void Start()
{
player=FindObjectOfType();
}
私有void更新()
{
playerRange=Physics2D.OverlapperCircle(transform.position、playerRange、playerLayer);
if(播放范围)
{
transform.position=Vector3.moveToward(transform.position,player.transform.position,moveSpeed*Time.deltaTime);
}
翻转();
}
私有无效OnDrawGizmosSelected()
{
Gizmos.DrawSphere(transform.position,playerrorge);
}
私有void Flip()
{
if(transform.position.x>0&&!Right | | transform.position.x<0&&Right)
{
右=!右;
Vector3 theScale=transform.localScale;
比例x*=-1;
transform.localScale=比例;
}
}
}
看看你的代码,敌人所面对的方向取决于敌人在世界上的位置(因为你使用的是transform.position的x分量)。如果您的敌人x位置为正,则右布尔值为真,否则为假(也不考虑0的情况)
因为在这个代码片段中,唯一可以移动敌人的是Vector3.MoveToward,当玩家在射程内时,我怀疑发生了什么,当玩家靠近时,敌人移动,x位置值从负变为正(或相反),翻转精灵
现在,把精灵的方向和敌人的位置联系起来并不是你想做的事情。相反,你想让敌人面对它前进的方向。这可以通过有一个速度参数来实现,你可以使用这个参数来移动你的敌人,它可以告诉你他移动的方向(以及速度)。如果你想保持移动的方向,那么你需要找出它使你移动的方向,并相应地翻转精灵。以下是基于您的代码的代码示例:
private void Update()
{
playerinRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerinRange)
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, moveSpeed * Time.deltaTime);
Flip(player.transform.position.x - transform.position.x);
}
}
private void Flip(float direction)
{
Right = (direction >= 0);
Vector3 theScale = transform.localScale;
theScale.x = Mathf.Abs(theScale.x) * Mathf.Sign(direction);
transform.localScale = theScale;
}