旋转然后在 Unity 中沿随机方向移动对象

Rotate then move object in Random direction in Unity

我正在尝试在 Unity 中创建一个脚本,当另一个对象接触到它时,它会抓住该对象,沿随机方向旋转它,然后启动它,但我只想旋转并启动另一个对象z 轴.

这是我的脚本:

public BallController ballController;
private GameObject ball;
private Rigidbody2D ballRb;

 void OnTriggerEnter2D(Collider2D other)
{
    ball = other.gameObject;
    ballRb = ball.GetComponent<Rigidbody2D>();
    ball.transform.position = this.transform.position;
    // Freeze the ball
    ballRb.velocity = Vector2.zero;
    // Rotate the ball
    ball.transform.rotation = Quaternion.Euler(0, 0, Random.Range(0, 360));
    // Start moving the ball again
    ballRb.velocity = ballRb.velocity * ballController.bulletSpeed * Time.deltatime;

}

另一个脚本(球)有一个 Ridgidbody 并由另一个对象发射到这个脚本中,脚本让球按照我想要的方式旋转,但它不会让球再次移动。

在编辑器中设置了 ballController,而 bulletSpeed 只是我希望球移动的整数(当前设置为 6)。

在处理 Rigidbody2D 时,您不应使用 transform 来设置旋转,而应使用 ballRb.rotation.

稍后您正在使用

ballRb.velocity = ballRb.velocity * ballController.bulletSpeed * Time.deltatime;

但就在你设置之前

ballRb = Vector2.zero;

所以乘法结果是 Vector2.zero。在这个一次性作业中添加 Time.deltaTime(顺便说一句,错别字)也没有任何意义。

此外,如果您删除这条线,则在分配新速度时不会考虑新的旋转。

velocity 在全局 space 中。你也不能使用例如transform.right 作为新方向,因为变换未更新.. Rigidbody2D 是.. 因此您可以使用 GetRelativeVector 以便在旋转后设置新的局部方向

private void OnTriggerEnter2D(Collider2D ball)
{
    // The assignment of the GameObject
    // was kind of redundant except
    // you need the reference for something else later

    var ballRb = ball.GetComponent<Rigidbody2D>();

    // set position through RigidBody component
    ballRb.position = this.transform.position;

    // Rotate the ball using the Rigidbody component
    // Was the int overload intented here? Returning int values 0-359
    // otherwise rather use the float overload by passing float values as parameters
    ballRb.rotation = Random.Range(0f, 360f);

    // Start moving the ball again
    // with a Vector different to Vector2.zero 
    // depending on your setup e.g.
    ballRb.velocity = ballRb.GetRelativeVector(Vector2.right * ballController.bulletSpeed);
}

小演示

对于墙壁,顺便说一句,我使用了非常相似的东西:

var ballRb = ball.GetComponent<Rigidbody2D>();
var newDirection = Vector2.Reflect(ballRb.velocity, transform.up);
ballRb.rotation = ballRb.rotation + Vector2.SignedAngle(ballRb.velocity, newDirection);
ballRb.velocity = newDirection.normalized * ballController.bulletSpeed;