像LookAt(x,Vector3.Right)那样让slerp工作

时间:2012-10-11 15:06:31

标签: transform unity3d quaternions side-scroller

我一直在为一个sidecroller射击游戏工作。我已经让我的sidescroller射手角色环顾四周:

chest.LookAt(mousepos, Vector3.right);

&安培;

chest.LookAt(mousepos, Vector3.left);

(当角色向右转动时左侧和右侧角色左侧)

因此它不会瞄准任何其他轴...但是当鼠标越过角色的中间而不是它周围时,它会获得旋转以在帧之间进行小的传输并且它不会一直到达那里......它只是像LookAt那样传送到正确的旋转。

那么问题是,如何使用与Time.deltTime一起工作的任何四元数slerp与LookAt(x,Vector3.Right)一样工作?我必须有Vector3.right并离开,所以它将通过1轴移动。

非常感谢帮助我的人。 :)

1 个答案:

答案 0 :(得分:1)

我会有一个目标向量和一个开始向量,当用户将鼠标移到角色的左侧或右侧时设置它们,然后在更新函数中使用它们之间的Vector3.Slerp

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);
}