欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity角色移动和帧动画播放

程序员文章站 2022-03-31 20:44:19
...

Learning Tips

角色移动模板

    public float moveSpeed;
    //输入信号值
    public float Dup;
    public float Dright;
    //玩家移动意图
    private float targetDup;//竖直方向
    private float targetDright;//水平方向
    //Mathf.SmoothDamp的ref参数
    private float velocityDup;
    private float velocityDright;
    //自定义按键
    public string keyUp = "w";
    public string keyDown = "s";
    public string keyLeft = "a";
    public string keyRight = "d";
    void Update(){
        //玩家移动意图 得到0 1的移动信号
        targetDup = (Input.GetKey(keyUp) ? 1.0f : 0) - (Input.GetKey(keyDown) ? 1.0f : 0);
        targetDright = (Input.GetKey(keyRight) ? 1.0f : 0) - (Input.GetKey(keyLeft) ? 1.0f : 0);
        //对移动意图值进行平滑插值计算 得到平滑渐变的位移值
        //微分位移值
        Dup = Mathf.SmoothDamp(Dup, targetDup, ref velocityDup, 0.1f);
        Dright = Mathf.SmoothDamp(Dright, targetDright, ref velocityDright, 0.1f);//y WS
        //移动
        transform.Translate(new Vector3(Dright,Dup,transform.position.z)*moveSpeed*Time.deltaTime);
    }

播放帧动画的帧控制器

    public int fps = 10;//fps
    public float timer=0;

    public Sprite[] sprites;//存储图片帧数组
    public SpriteRenderer sr;
    
    void Start() {
        sr = GetComponent<SpriteRenderer>();//获取组件
        moveSpeed = 5;
    }
    void Update(){
        timer += Time.deltaTime;
        //1/fps=一帧所需时间 (timer/一帧所需时间)再取整得到当前帧索引
        int frameIndex = (int)(timer / (1.0f / fps)) %2;
            //frameIndex %= 2;
        sr.sprite = sprites[frameIndex];
    }

防止忘记,记录下来,随时温习