【问题标题】:How to control the direction of where the bouncing ball is going如何控制弹跳球的运动方向
【发布时间】:2019-04-05 22:18:31
【问题描述】:

我想做一个弹跳球游戏,我必须控制(连续弹跳的)球的行进方向。问题是,通过增加力,球的速度越来越快,我试图控制它越远,因为刚体上的摩擦力必须为零,我正在使用 Rigidbody().AddForce()。如何在不过度用力的情况下移动它? 如何让弹跳球朝我想要的方向弹跳(移动)? 我不想使用动画,游戏将基于各种物理事件。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour{
public Color[] colors;
private Renderer renderer;

private void Awake(){
    renderer = this.GetComponent<Renderer>();

    InvokeRepeating("ChangeColor", 0, 3f);
}

private void FixedUpdate()
{
    MoveBall();
}

void ChangeColor(){
    renderer.material.color = colors[Random.Range(0, colors.Length)];
}
void MoveBall(){
    Debug.Log(GetComponent<Rigidbody>().velocity.magnitude);

        if (Input.GetKey("w"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, 1) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }
        if (Input.GetKey("s"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -1) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }
        if (Input.GetKey("a"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(-1, 0, 0) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }
        if (Input.GetKey("d"))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(1, 0, 0) * (30f - (GetComponent<Rigidbody>().velocity.magnitude*9)));
        }

}

}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以设置速度限制,使其不会加速超过您所需的最大值:

    rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);
    

    或者,如果它不破坏您想要的物理方法,您可以直接修改对象的速度,并使用以下方法消除任何加速度:

    rigidbody.velocity = new Vector3();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2013-05-05
      • 2012-07-28
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多