- Home /
How to control missile/knife (Quaternion.Euler)
Hi,
I am making a game where the player is able to throw a knife and then control the knife, from a first person view, by moving the mouse. When the player throws a knife, a new "knife-camera" is instatiated, and I can see that it is looking in the same direction as the player (which is what I want). But as soon as the first update (within the knife script) is called, the view shifts to some default position.
The update function can be seen here:
void Update()
{
if (!hasHit )
{
if (isBeingControlled)
{
//float mousePosX = Input.GetAxis("Mouse X") + screenCenter.x;
//float mousePosY = Input.GetAxis("Mouse Y") + screenCenter.y;
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
transform.position += transform.forward * speed * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Q))
{
isBeingControlled = false;
speed = 20f;
ActivatePlayer();
}
}
else
{
transform.position += transform.forward * speed * Time.deltaTime;
}
}
}
If I remove, transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
, I can see that the knife is flying in the "correct" direction, but then I cannot control the knife.
Am I missing something, or can I do this in an easier way.
Thank you in advance!
Answer by unity_ek98vnTRplGj8Q · Apr 06, 2021 at 04:34 PM
When you call transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
you are overwriting whatever rotation it held before. Instead of setting the value absolutely, you want to make incremental, relative changes to the rotation.
Try instead something like transform.localRotation = transform.localRotation * Quaternion.Euler(xRotation, yRotation, 0);
I agree that the transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
is overwriting the initial rotation and that I have to find a way to make the rotation incremental, but unfortunately your suggestion did not work.
Answer by skulldj1 · Apr 06, 2021 at 07:20 PM
I found the root of the problem. I initialize xRotation and yRotation as 0f but they should be set to the rotation of the player.