我刚刚开始使用Unity和Visual Studio制作游戏,我有点困惑为什么我的 Speed 值始终设为零,即使我将其设置为另一个变量也是如此。
<?php ?>
这是我的 speed 值始终为零的脚本
<?= ?>
答案 0 :(得分:1)
Start
仅发生一次。
启用脚本之前,在框架上调用开始 第一次调用Update方法。
忽略其他所有内容,我想您希望它更新Update
中每一帧的speed
如果启用MonoBehaviour,则会在每一帧调用更新。
private void Update()
{
\\ i though the code below will set my speed equal to my finalSpeed but it still 0
speed = ballista.GetComponent<Ballista>().finalSpeed;
Vector2 mousePos = Input.mousePosition;
Debug.Log("speed: " + speed);
rgBody2D.AddForce(mousePos * speed * Time.deltaTime);
}
答案 1 :(得分:1)
速度= ballista.GetComponent()。finalSpeed;
应该进来
void Update(){
}
阻止而不是进入
void Start() {
}
因为空启动仅运行一次,并且在那个时间点速度为零 希望对您有所帮助:)
答案 2 :(得分:1)
与其他人在这里所说的不同,您实际上不想要在Update
中这样做。
您的目标是一次给刚生成的箭头一个开始速度,而不是一个连续的力。
我认为这里的问题还有其他性质:
您始终在从给定的预制中生成第二个脚本的 new 实例。该预制件似乎包含对Ballista
prefab 实例的引用。至少您永远不会为ballista
分配新的值!永远不会更新finalSpeed
的地方可能是错误的参考。
您首先执行Shoot
,然后设置finalSpeed
->,即使它是正确的引用,您也总是得到错误的finalSpeed
值!>
我实际上将更改您的两个脚本,以使您的箭头实例受Ballista
控制,而不是让每个生成的箭头自己轮询速度:
public class Ballista : MonoBehaviour
{
public Transform firePoint;
// By giving it the correct type here you don't need GetComponent later
public Rigidbody2D arrowPrefab;
public float startTimeHold;
public float arrowSpeed = 100f;
// I personally would add aax value and clamp since to fast RigidBodies can break collision detection eventually
public float maxArrowSpeed = 300;
private void Update()
{
if (Input.GetKeyDown(KeyCode.M))
{
startTimeHold = Time.time;
}
if (Input.GetKeyUp(KeyCode.M))
{
var holdDownTime = Time.time - startTimeHold;
// get the speed before you shoot
// Here personally I would clamp to be sure the arrow is never faster than maxArrowSpeed
// regardless of how long the user held the button pressed
var finalSpeed = Mathf.Min(holdDownTime * arrowSpeed, maxArrowSpeed);
Debug.Log("holddowntimeis: " + holdDownTime);
Debug.Log("final speed is: " + finalSpeed);
// pass in your speed
Shoot(finalSpeed);
}
}
private void Shoot(float speed)
{
// Instantiate anyway returns the type of the given prefab
// which now is a Rigidbody2D
var arrow = Instantiate(arrowPrefab, firePoint.position, firePoint.rotation);
// Directly set the speed from here
// -> your arrow doesn't even need an extra component
// Since you already spawned it with the correct rotation you maybe don't even need the mouse position thing
// AddForceRelative adds a force in the local space of the arrow so if the rotation is correctly
// this simply adds the force in its forward direction
// Note that also using Time.deltaTime actually only makes sense if you set something continuously
// For a one-time force you wouldn't need it, rather adjust your arrowSpeed field
arrow.AddForceRelative(Vector2.forward * speed);
}
}
除了使用AddForce
或AddForceRelative
之外,您实际上还可以简单地设置目标速度:
arrow.velocity = Vector2.forward * speed;
由于您没有连续进行更新,因此这非常好,并且可以更轻松地预测实际目标速度,因为在添加力时必须考虑质量和摩擦。当然,您将不得不相应地调整arrowSpeed
(和evtl maxArrowSpeed
),使其不再代表力,而是代表单位为单位的实际速度。
我希望我的观点足够清楚,不要犹豫,问是否还有不清楚的地方;)