[英]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
(typo btw)是沒有意義的。
同樣,如果刪除了這條線,則在分配新速度時不會考慮新的旋轉。
velocity
在全局空間中。 您也不能使用例如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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.