【发布时间】:2020-11-15 09:57:46
【问题描述】:
我正在制作一个关于蛋狗的游戏,它们可以互相射击来和我兄弟一起玩(他出于某种原因非常喜欢蛋狗)。这将是私人的。它将有一个自动瞄准机制,可以瞄准最近的敌人。这个想法是当玩家使用触发对撞机进入您的范围时,该玩家将被添加到目标列表中,然后一个方法将计算最近的玩家。
我写了一些代码,它运行得几乎完美,但是当列表被修改时,播放器随机加速。我不知道为什么会这样。我尝试注释掉很多代码并从其他地方修改列表,它似乎只有在修改列表时才会发生。这是一些代码:
这是我的主要 EggDog 控制器:
using UnityEngine;
public class EggdogController : MonoBehaviour
{
Rigidbody2D rb;
Animator an;
public int PlayerNo;
public float speed;
public Transform pickupParent;
public Transform currentPickupTarget;
public List<Transform> targetList = new List<Transform>();
public Transform currentTarget;
void Awake(){
rb = GetComponent<Rigidbody2D>();
an = GetComponent<Animator>();
}
void Update(){
Move();
Boba();
PickTarget();
}
void Move(){
Vector3 move = new Vector3(0,0,0);
move.x = Input.GetAxisRaw("Horizontal" + PlayerNo.ToString());
move.y = Input.GetAxisRaw("Vertical" + PlayerNo.ToString());
rb.velocity = move*speed*Time.deltaTime;
}
void Boba(){
an.SetBool("longing", Input.GetAxisRaw("Boba" + PlayerNo.ToString()) == 1);
}
void PickTarget()
{
if(targetList.ToArray().Length > 0)
{
float currentDistance = -69f;
foreach (Transform potato in targetList.ToArray())
{
float thistance = Vector3.Distance(transform.position, potato.position);
if(currentDistance == -69f)
{
currentDistance = thistance;
currentTarget = potato;
}
else
{
if(currentDistance > thistance)
{
currentTarget = potato;
}
}
}
}
}
}
这是我的 EggdogTriggerTarget 脚本,附加到带有触发器碰撞器的子对象:
using System.Collections.Generic;
using UnityEngine;
public class EggdogTriggerTarget : MonoBehaviour
{
EggdogController parent;
private void Awake()
{
parent = transform.parent.GetComponent<EggdogController>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
parent.targetList.Add(other.transform);
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
bool exists = false;
foreach (Transform tr in parent.targetList.ToArray())
{
if (tr == other.transform)
{
exists = true;
}
}
if (exists)
{
parent.targetList.Remove(other.transform);
}
}
}
}
没有错误消息或任何在线内容。如果您能提供帮助,我会很高兴。
【问题讨论】:
-
您的
rigidbody.velocity仅受Input影响。与目标列表无关。无论如何,您需要修改FixedUpdate()中的刚体,并且您不应该明确修改速度,请考虑使用Rigidbody.AddForce() -
@luvjungle 谢谢!将我的 Move() 方法转移到固定更新修复它!
-
我添加了我的评论作为答案。请标记为有帮助
标签: c# list unity3d rigid-bodies