I made a game object and attached a script to it. I need to rotate and move the object in a straight line, depending on the rotation. I made a turn, but I have problems with movement. Any solutions?
//Rotation
if (Input.GetAxis("Rotation") > 0) {
transform.Rotate(Vector3.back, turnSpeed * Time.deltaTime);
}
else if (Input.GetAxis("Rotation") < 0)
{
transform.Rotate(Vector3.back, -turnSpeed * Time.deltaTime);
}
//Velocity
if (Input.GetAxis("Thrust") != 0) {
rb.AddForce(Vector3.forward * Time.deltaTime * Speed);
}
else if (Input.GetAxis("Thrust") <= 0.1f){
rb.velocity = new Vector2(0, 0);
}
Rigidbody.AddForce
applies the vector as force in world space. So, you need to give it a vector that is in the world space direction of the transform's forward. Luckily, that's as simple as usingtransform.forward
, transform.up
, or transform.right
or a negation of one of them instead of Vector3.forward
:
//Rotation
if (Input.GetAxis("Rotation") > 0) {
transform.Rotate(Vector3.back, turnSpeed * Time.deltaTime);
}
else if (Input.GetAxis("Rotation") < 0)
{
transform.Rotate(Vector3.back, -turnSpeed * Time.deltaTime);
}
//Velocity
if (Input.GetAxis("Thrust") != 0) {
Vector3 frontDirection;
// probably one of these for a 2D game:
frontDirection = transform.right;
//frontDirection = -transform.right;
//frontDirection = transform.up;
//frontDirection = -transform.up;
rb.AddForce(frontDirection * Time.deltaTime * Speed);
}
else if (Input.GetAxis("Thrust") <= 0.1f){
rb.velocity = new Vector2(0, 0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.