尽管速度变化统一,球仍以相同的速度移动
问题描述:
我创建了乒乓球,一切都很好,但是,我希望在那里能够在球速变化的地方进行加速。我有一个速度变量,但它似乎只改变球开始的速度,然后速度保持不变。这是球形面板的图像。 尽管速度变化统一,球仍以相同的速度移动
,这里是球脚本
public float ballVelocity = 1000;
Rigidbody rb;
bool isPlay;
int randInt;
public Vector3 velocity;
float elapsed = 0;
private bool onLeft;
public Vector3 startPos = new Vector3(0, 0, 0);
void Awake()
{
rb = GetComponent<Rigidbody>();
randInt = Random.Range(1,3);
velocity = new Vector3 (ballVelocity, ballVelocity, 0);
}
void Update()
{
if (rb.transform.position.x < GameObject.FindGameObjectWithTag ("paddle").transform.position.x) {
print ("game over");
}
if (rb.position.x < 0)
onLeft = true;
else
onLeft = false;
elapsed += Time.deltaTime;
rb.drag = 0;
print(onLeft);
if (elapsed > 5) {
//rb.velocity *= .5f;
elapsed = 0;
}
rb.maxDepenetrationVelocity = ballVelocity;
if (Input.GetMouseButton(0) && isPlay == false)
{
transform.parent = null;
isPlay = true;
rb.isKinematic = false;
if (randInt == 1)
{
rb.AddForce(new Vector3(ballVelocity, ballVelocity, 0));
}
if (randInt == 2)
{
rb.AddForce(new Vector3(-ballVelocity, -ballVelocity, 0));
}
}
}
}
里面的代码不管是什么我都试过了,还是什么我已经看过了,似乎没有任何帮助。请有人帮我这个。谢谢你的时间!
答
改变对象速度的最简单方法是用rb.velocity获取当前速度,用.normalized将其标准化,然后将rb.velocity设置为该矢量乘以您希望球移动的速度在。
下面是这样一个例子代码:
void ChangeSpeed(float speed)
{
Vector3 dir = rb.velocity.normalized;
rb.velocity = dir * speed;
}
如果你的系统是这样做后无损(100%反弹,不拖,等等),球会留在那速度,直到你改变它再次。
非常感谢你 – Luke