【发布时间】:2018-05-27 23:08:01
【问题描述】:
所以我正在统一制作一个游戏,其中一个对象将朝玩家鼠标点击的方向(单位向量)冲刺。根据我在检查器中创建和设置的冲刺速度和冲刺时间变量,它通常会起作用,因为物体冲刺的距离和它的速度通常是恒定的。但是,有时对象的冲刺距离会关闭。我试图通过记录破折号距离和物体的速度来解决问题,我发现有时一个或两个变量由于某种原因我丢失了一些随机值。尽管变量是相同的数字,但在大多数点击中。这是我的代码:
[RequireComponent(typeof(Rigidbody2D))]
public class DashController : MonoBehaviour
{
Rigidbody2D rigidbody;
public float dashSpeed;
public float dashTime; //dash time for inspector use
float codeDashTime; //dash time for code use
bool dashing;
Vector2 direction;
Vector2 startPosition;
Vector2 endPosition;
float distance;
private void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
codeDashTime = dashTime;
dashing = false;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
//need to subtract the current postion from the target postion
direction = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - this.transform.localPosition);
startPosition = this.transform.localPosition; // used to see the distance player dashes
dashing = true;
}
if (dashing)
{
Dash();
}
}
void Dash()
{
if (codeDashTime > 0)
{
rigidbody.velocity = direction.normalized * dashSpeed;
codeDashTime -= Time.deltaTime;
}
else
{
Debug.Log(rigidbody.velocity.magnitude);// used to see the velocity the player travels at
Debug.Log(direction.normalized.magnitude);
rigidbody.velocity = Vector2.zero;
endPosition = this.transform.localPosition; // used to see the distance player dashes
distance = Vector2.Distance(startPosition, endPosition);// used to see the distance player dashes
Debug.Log(distance); // used to see the distance player dashes
dashing = false;
codeDashTime = dashTime;
}
}
}
对不起,如果我的代码有点混乱。我一直在移动很多东西,测试不同的解决方案,但没有任何效果。我最好的猜测是,也许框架的某些东西弄乱了 codeDashTime,但我对统一和 C# 太陌生了,不知道。任何帮助表示赞赏,谢谢。
【问题讨论】:
标签: c# unity3d velocity rigid-bodies