简体   繁体   中英

Unity 3D move object around orbit with user inputs

I have a spaceship which flies around planets orbit by this script:

Update() {
    transform.RotateAround(planet.transform.position, Vector3.up, speed * Time.deltaTime);
}

But I don't understand how to add user inputs (Input.GetAxis("Horizontal") and Input.GetAxis("Vertical")) to this script so user can control spaceship's movement. How can I move spaceship around orbit using user input (arrows) ?

EDIT: Camer follows ship from behind. Ship is moved forward by some force (speed) on planet's orbit (to simplify, it's just a circle). I want user to be able to change direction of movement (left\\right) like in the pucture (from D1 to D2).

例

太空飞船在行星轨道上

This task can be split into two parts. First is rotating the ship based on user input. The second is to change our method of orbiting to account for the rotation of the ship so that it moves in the direction that it is facing.

We can solve part one by using a Transform.Rotate call. Since we want the bottom of the ship to always face the planet, we want to rotate along the ship's "Up" axis. For our Input axis, the "Horizontal" will likely be the most intuitive. It will look something like this:

transform.Rotate(Vector3.forward, Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime);

For part two, it is important to realize that Transform.RotateAround uses the world space, and not the local space. By making it use the local space of the ship, it will account for the ship's rotation such that the ship will move in the direction that it is facing, rather than moving in an independent direction. We can do this by using the Transform.TransformDirection function. It will look something like this:

transform.RotateAround(planet.transform.position, transform.TransformDirection(Vector3.up), speed * Time.deltaTime);

Combining these in an update function worked for me in a quick test.


In addition, if we want the ship to strafe from side to side without doing any local rotation of the ship, we can do it with another Transform.RotateAround call, like so:

transform.RotateAround(planet.transform.position, transform.TransformDirection(Vector3.right), Input.GetAxis("Horizontal") * strafeSpeed * Time.deltaTime);

(Answer edited for question edit)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM