我的敌人脚本在Unity中表现不佳



所以,我统一写了这个敌人的剧本,但是我的敌人在飞,他违反了万有引力定律,我不太喜欢。运动方法有什么问题吗?请帮帮我!他的体重是100,重力刻度设为32。我真不知道为什么会这样。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CobraScript : MonoBehaviour {
private GameObject Player;
private Rigidbody2D Rb;
public float Speed;
private float AttackDelay;
public GameObject Walking;
public GameObject AttackPoint; 
private AudioSource Src;
public AudioClip Clip;
private bool Aggro;
public LayerMask PlayerLayer;
public float AggroRange;
public float AttackRange;
public float ReturnSpeed = 0.3f;
private bool ShouldWalking = true;
void Start()
{
Player = GameObject.Find("DrawCharacter");
Src = Camera.main.GetComponent<AudioSource>();
Rb = GetComponent<Rigidbody2D>();
}
void Update()
{
AttackDelay -= Time.deltaTime;
Collider2D[] PlayerFind = Physics2D.OverlapCircleAll(transform.position, AggroRange, PlayerLayer);
if (PlayerFind.Length > 0)
{
Aggro = true;
}

if (Aggro)
{
if (ShouldWalking)
{
gameObject.GetComponent<Animator>().Play("XenusRun");
Walking.SetActive(true);
}else
{
Walking.SetActive(false);
}
Collider2D[] PlayerAttack = Physics2D.OverlapCircleAll(AttackPoint.transform.position, AttackRange, PlayerLayer);
if (PlayerAttack.Length > 0 && AttackDelay <= 0)
{
StartCoroutine(Attack());
AttackDelay = 3;
}
if (Player.transform.position.x < this.transform.position.x)
{
transform.localScale = new Vector3(-1, 1, 1);
}else
{
transform.localScale = new Vector3(1, 1, 1);
}
Vector3 dir = Player.transform.position - transform.position;
---->        Rb.MovePosition(transform.position + dir * Speed);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(AttackPoint.transform.position, AggroRange);
Gizmos.DrawWireSphere(AttackPoint.transform.position, AttackRange);
}
private IEnumerator Attack()
{
ShouldWalking = false;
GetComponent<Animator>().Play("XenusAttack");
Speed = 0;
yield return new WaitForSeconds(0.4f);

Src.PlayOneShot(Clip);
AttackPoint.SetActive(true);

yield return new WaitForSeconds(0.2f);

ShouldWalking = true;
AttackPoint.SetActive(false);
yield return new WaitForSeconds(ReturnSpeed);
Speed = 0.059f;
}
}

‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌

您是否不小心选中了" Use gravity ";选项在你的RigidBody组件?

如果它不起作用,试着在你的敌人的检查器中禁用你的脚本,看看你的敌人在播放时间是否仍然在下降。

如果他没有摔倒,那么你的问题不是来自你的代码,而是来自刚体。

否则,如果他正在下落,那么你的问题确实在你的代码中。我建议用Rb.velocity = dir * Time.fixedDeltaTime * Speed;代替Rb.MovePosition(transform.position + dir * Speed);


此外,永远不要在Update()方法中放入与物理相关的代码,特别是如果您不使用Time.deltaTime。把它放在FixedUpdate()中,这样你的敌人的速度就不会依赖于电脑的表现。你可以在这里找到更多信息。
最后,你的变量应该是camelCase而不是PascalCase。

最新更新