示例#1
0
    void FixedUpdate()
    {
        // 获取水平输入
        float h = InputEx.GetAxis("Horizontal");

        // 设置动画的速度为水平方向的输入值
        anim.SetFloat("Speed", Mathf.Abs(h));
        // 如果对象在x轴上的当前方向刚体力小于最大速度,则为对象施加刚体力
        if (h * GetComponent <Rigidbody2D>().velocity.x < maxSpeed)
        {
            // 给玩家添加刚体力,力的大小为水平方向乘以moveForce, 这里通过h的使用,不需要判断力的方向了
            GetComponent <Rigidbody2D>().AddForce(Vector2.right * h * moveForce);
        }
        // 如果对象在x轴上的当前方向刚体力大于最大速度
        if (Mathf.Abs(GetComponent <Rigidbody2D>().velocity.x) > maxSpeed)
        {
            // 使用新的向量来设置速度,通过Mathf.Sign来获取角色的方向乘以最大速度来确定x轴上的速度,保持原方向
            GetComponent <Rigidbody2D>().velocity = new Vector2(Mathf.Sign(GetComponent <Rigidbody2D>().velocity.x) * maxSpeed, GetComponent <Rigidbody2D>().velocity.y);
        }

        // 判断角色是否需要转身
        if (h > 0 && !facingRight)
        {
            Flip();
        }
        else if (h < 0 && facingRight)
        {
            Flip();
        }

        // 角色跳跃处理
        if (jump)
        {
            // 播放跳跃动画
            anim.SetTrigger("Jump");
            // 随机播放一个音效
            int i = Random.Range(0, jumpClips.Length);
            AudioSource.PlayClipAtPoint(jumpClips [i], transform.position);
            // 为角色跳跃增加向上的刚体力
            GetComponent <Rigidbody2D> ().AddForce(new Vector2(0f, jumpFore));
            // 重置jump为false,以免为角色不断的增加向上刚体力
            jump = false;
        }
    }