Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get slerp to work just as LookAt(x,Vector3.Right) does

Ive been working over a sidescroller shooter game. Ive got my sidescroller shooter character to look around with these :

chest.LookAt(mousepos, Vector3.right);

&

chest.LookAt(mousepos, Vector3.left);

(Left when the character is turned to the left and right when the character is turned to the right)

so it wont aim in to any other axis... But when the mouse gets to cross the middle of the character and not around it it gets the rotation to make a small transportation between frames and it wont get all the way to there.. It'll just teleport to its correct rotation like LookAt should.

Well the question is, how do I get any quaternion slerp which works with a Time.deltTime to work as same as LookAt(x,Vector3.Right)? I must have the Vector3.right and left so it'll move trough 1 axis.

Many thanks to anyone who helps me out. :)

like image 233
Ben Rokah Avatar asked Nov 24 '25 01:11

Ben Rokah


1 Answers

I would have a target vector and a start vector, and set them when the user takes their mouse to the left or right of the character, then use Vector3.Slerp between them in the update function.

bool charWasFacingLeftLastFrame = false.
Vector3 targetVector = Vector3.zero;
Vector3 startVector = Vector3.zero;
float startTime = 0f;
float howLongItShouldTakeToRotate = 1f;

void Update () {
    Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector3 characterPos = character.transform.position;

    //check if mouse is left or right of character
    if(mouseWorldPos.x < characterPos.x) {
        //char should be facing left
        //only swap direction if the character was facing the other way last frame      
        if(charWasFacingLeftLastFrame == false) {
            charWasFacingLeftLastFrame = true;
            //we need to rotate the char
            targetVector = Vector3.left;
            startVector = character.transform.facing;
            startTime = Time.time;
        }
    } else {
        //char should be facing right
        //only swap direction if the character was facing the other way last frame      
        if(charWasFacingLeftLastFrame == true) {
            //we need to rotate the char;
            charWasFacingLeftLastFrame = false
            targetVector = Vector3.right;
            startVector = character.transform.facing;
            startTime = Time.time;
        }
    }

    //use Slerp to update the characters facing
    float t = (Time.time - startTime)/howLongItShouldTakeToRotate;
    character.transform.facing = Vector3.Slerp(startVector, targetVector, t);
}
like image 124
Tom Harris Avatar answered Nov 26 '25 15:11

Tom Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!