【Unity】控制人物移动

2D

1.制作移动动画:Idle、Run、Jump

2.物理控制人物运动:

  • 水平方向,根据input的axis给力,提供加速度。
  • 修改LinerDrag,调整停下来的加速度。
  • 重力变大,会使得摩擦力变大,难以移动。可以建立一个physics material,将摩擦力设置为0.

3.使用水平速度作为参数来调整走和跑动画之间的过渡。anim.setFloat();

4.反向运动修改localScale的z值为负即可。

5.跳跃:

设置Ground,只有在Ground上才能跳。

在地面上,且按下空格键的时候,将player的Y轴速度设置为30或更大。

根据rigidbody.velocity.y的正负来判断应该切换到哪个动画。>5,jumpUp,<-5,jumpDown,在二者之间,idle。

任何状态都可以切换到JumpUP,包括walk和run。

3D

1.CharacterController的Move方法。把Vector3(h,0,v)作为前进方向。

2.跳跃:把前进方向的Y值调高,然后再由重力影响落下。

3.行走动画,不勾选root。

【1】Rigidbody

移动:

rigibody.velocity=new Vector3(h,vel.y,v);

动画:

if(rigidbody.velocity.magnitude>0.5f){anim.setBool()};

转向:

if( Mathf.Abs(h)>0.05f || Mathf.Abs(v) >.05f){

        transform.rotation = Quaternion.LookRotation(new Vector3(-h,0,-v));

  }

跳跃

transform.rotation = Quaternion.LookRotation(Vector3.forward, Vector3.up);
         if (Input.GetButtonDown("Jump"))
        {
            if (ground == true)
            {                   
                GetComponent<Rigidbody>().velocity += new Vector3(0, 5, 0);
                GetComponent<Rigidbody>().AddForce(Vector3.up * mJumpSpeed);
                ground = false;
            }
        }

【2】Transform

移动:

tranform.localPosition+=new Vector3(h*speed,0,v*speed);

转向:得到当前方向和目标方向的夹角,旋转到对应角度

Vector3.Angle(targetDir,nowDir);

transform.Rotate(Vector3.up*angle*Time.deltaTime*rotateSpeed);


Vector3 targetDir=new Vector3(h,0,v);

Vector3 nowDir=transform.forward;

float angle=Vector3.Angle(targetDir,nowDir);

if(angle>180){

    angle=360-angle;

    angle=-angle;

}

transform.Rotate(Vector3.up*angle*Time.deltaTime*rotateSpeed);

【3】动画:

移动:直接在locomotion和idle动画之间切换,speed<0.1f就会是idle。

if(Mathf.Abs(h)>0.1f){

    float newSpeed=Mathf.Lerp(anim.GetFloat("speed"),5.6f,moveSpeed*Time.deltaTime);

    anim.SetFloat("speed",newSpeed);

}else{

    float newSpeed=Mathf.Lerp(anim.GetFloat("speed"),0f,stopSpeed*Time.deltaTime);

    anim.SetFloat("speed",stopSpeed);

}

【4】CharacterMove

一些问题:

关于动画的问题:1.animation之间的切换 2.layer和BlendTree

发布了154 篇原创文章 · 获赞 45 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_36622009/article/details/87983693