Trouble with Rotations and Transform.LookAt() (I think!)
Hi everyone! Sorry that this is a crosspost from the Unity3D Reddit, but it hasn't got much (any) traction there. Since there isn't a very elegant way to share video here (that I know of!), you can see the problem here on the Reddit thread—sorry again if that's bad manners to just link to over there! This is my first Unity project outside of a couple of tutorials, and I'm making an isometric space shooter with WASD and mouse controls. I'm running into an issue with my "aiming" system. There's a reticle that's moved with the mouse, that the player's ship (white) is made to rotate towards, essentially with the Transform.LookAt() function, meanwhile the movement is controlled with RigidBody.AddForce(). These both work well, but as soon as the ship is moved and there is rotation, the ship no longer fires it's projectiles correctly. You can see in the included video that projectiles are fired in the direction I would expect, but as soon as the ship is moved, something goes wrong and the projectiles are fired in all sorts of directions that don't seem to make sense. Here's the function (called from LateUpdate() in the script on the reticle) that rotates the ship:
private void AdjustPlayerAim()
{
player.transform.LookAt(aim.transform);
}
And here's the relevant movement code in the script living on the player's ship (CheckForInput() is called in Update()):
private void CheckForInput()
{
if (Input.GetButtonDown("Fire1"))
{
InvokeRepeating("Fire", 0f, 60f / fireRate);
}
else if (Input.GetButtonUp("Fire1"))
{
CancelInvoke();
}
if (Input.GetKey(KeyCode.A)) { Thrust(cameraLeft); print("Thrusting left"); }
if (Input.GetKey(KeyCode.D)) { Thrust(cameraRight); }
if (Input.GetKey(KeyCode.W)) { Thrust(cameraForward); }
if (Input.GetKey(KeyCode.S)) { Thrust(cameraBack); }
}
public void Thrust(Vector3 direction)
{
shipRigidbody.AddForce(direction * thrustForce * Time.deltaTime);
}
What I'm observing is that as soon as the ship moves, the game object where the projectiles are instantiated from gets its rotation completely screwed up. As you can see in the video, if I'm just staying still and rotating, everything works as I'd expect, but as soon as the ship moves it goes south. Here's an image of the rotation in the editor (with the mentioned game object selected):
What's frustrating is that when I have Local turned on in the editor, the rotation looks good! What's going on? Thanks again for your attention!
Answer by gusbmurphy · Oct 09, 2019 at 03:53 PM
Well, I solved it! Very silly mistake where I was giving the projectiles a velocity from a unit vector that didn't make any sense, just had to straighten that part out.