Rotate my spaceship in the right direction
Hi guys, I am making a game where I have a space ship. The Camera is under the space ship and is looking towards the bottom of it. The space ship is moving forward over the transform.up. My problem is that I cannot figure out how I can steer my space ship. I wrote some code but I can't seem to get it working can anyone help me please.
I want to use the camera and the mouse position and make a ray out of it. That part is working fine, now I want to allign the ship with the new vector, that is where the problems start showing up.
This is the code:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 newDir = (ship.position - ray.direction).normalized;
Vector3 newRight = Vector3.Cross(newDir, ship.forward);
Quaternion newUp = Quaternion.LookRotation(Vector3.Cross(newRight, newDir),newDir);
obj.rotation = Quaternion.Slerp(ship.rotation,newUp, Time.deltaTime);
I'm having trouble understanding the description of how your ship is moving. Is it 2 dimensional and the ship is moving left/right/up/down or is it 3 dimensional and the ship is moving forward into the screen?
It is a 3 dimensional ship and yes it is moving forward into the screen. The problem is that I can't steer it to left, right, up and down. Also the camera is underneath the ship in the ships local y direction. So to move it I translate the ship in the Y direction in its own space. And then the camera stays behind it and keeps looking at it.
Answer by LazyElephant · Dec 10, 2015 at 05:19 PM
With the following code I was able to get a cube moving in the way I believe you're looking for. I had the camera childed to the cube, but you should be able to use Camera.main.ScreenToWorldPoint to create the target vector.
Camera camera = GetComponentInChildren<Camera>();
Vector3 mousePosition = Input.mousePosition;
Vector3 target = camera.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, camera.farClipPlane));
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward, target-transform.position), Time.deltaTime);
Since you said the ship was moving in the Vector3.up direction, I set the LookRotation to keep the same forward direction and change the new up direction to the target point. If you were to change the ship to be moving in the forward direction instead, just change the last line to
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation( target-transform.position), Time.deltaTime);
Your answer
Follow this Question
Related Questions
Problem Instantiating a Prefab 1 Answer
Quaternion.Euler doesn't work right? 2 Answers
Verifying Euler to Quaternion calculations 1 Answer
Character rotation on ledge hanging 0 Answers
Quaternion lerp back and forth 0 Answers