Samrat Luitel
Samrat Luitel

Reputation: 379

How Quaternion gets multiplied with a vector?

I am working on a third person shooter. And I have found this code. But I cant make no sense with it. First it is multiplying Quaternion with "Vector3.forward" and compiler is showing nothing. And also can you make me clear about the main logic of this code. I know memorizing the code is not a good habit. So can you explain me the code. And what does that Quaternion.euler does, is that for changing euler to quaternion.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour {
    [SerializeField]
    Transform target;
    [SerializeField]
    float distance;
    [SerializeField]
    float targetheight;

    private float x = 0;
    private float y = 0;

    void LateUpdate()
    {

        y = target.eulerAngles.y;

        Quaternion rotation = Quaternion.Euler(x, y, 0);
        Debug.Log(rotation);
        transform.rotation = rotation;

        var postion = target.position - (rotation *Vector3.forward* distance + new Vector3(0, -targetheight, 0));
        transform.position = postion;
    }
}

Upvotes: 1

Views: 3516

Answers (1)

Crusha K. Rool
Crusha K. Rool

Reputation: 1502

Let's break it down:

y = target.eulerAngles.y;

This is Transform.eulerAngles() and gives you the current rotation of the target as Quaternion.

Then that rotation is reapplied to the target, but with the rotation around the Z-axis removed.

Quaternion rotation = Quaternion.Euler(x, y, 0);
Debug.Log(rotation);
transform.rotation = rotation;

This is Quaternion.Euler(x,y,z) and gives you a rotation from three degree values.

Last is the following calculation:

var postion = target.position - (rotation *Vector3.forward* distance + new Vector3(0, -targetheight, 0));
transform.position = postion;

Multiplying a Vector3 by a Quaternion means to apply the rotation to the vector. So in this case you'd rotate the forward vector based on the rotation of the target (without the Z-axis rotation, since we set that to 0 earlier). Then that resulting forward vector is multiplied by a certain distance to give us a point somewhere in front of the target's current facing direction and lowered according to the targetheight variable.

Lastly that calculation is subtracted from our own current position, basically performing a point reflection with the target being the point. The result is that we actually end up with a position that has a positive height (originally we were using a negative targetheight) and are behind the target's facing direction.

Upvotes: 5

Related Questions