所以我正在制作一个统一的游戏,其中一个物体将沿着玩家鼠标点击的方向(单位矢量)冲刺。根据我在检查器中制作和设置的破折号速度和破折号时间变量,它通常会起作用,因为在物体的虚线距离内,它的速度通常是不变的。但是,有时物体的短划线距离将会消失。我试图通过记录破折号距离和对象的速度来解决问题,我发现有时候其中一个或两个变量由于某种原因我都缺失了。虽然变量是相同的数字,但大多数点击次数。这是我的代码:
[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#才知道。感谢任何帮助。谢谢。
答案 0 :(得分:1)
所有物理应该在FixedUpdate上运行,输入通常用于Update,尝试将它们分开以获得更好的Rigidbody行为。