天天看點

【Unity】控制人物移動2D3D

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

繼續閱讀