我正在创造乒乓球,一切都运转良好,但是,我希望在球速度变化的地方进行加电。我有一个速度变量,但它似乎只改变球开始的速度,然后速度保持平坦。这是球面板的图像。
这是球脚本中的代码
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));
}
}
}
}
无论我尝试过什么,或者我看到了什么,似乎都没有任何帮助。请有人帮我这个。谢谢你的时间!
答案 0 :(得分:3)
更改对象速度的最简单方法是使用rb.velocity获取当前速度,使用.normalized对其进行标准化,然后将rb.velocity设置为该向量乘以您希望球进入的速度
以下是执行此操作的示例代码:
void ChangeSpeed(float speed)
{
Vector3 dir = rb.velocity.normalized;
rb.velocity = dir * speed;
}
如果您的系统无损(100%反弹,没有阻力等等),那么球将保持该速度,直到您再次更换为止。