unity自学之项目剖析(4)

来源:互联网 发布:linux初级运维面试题 编辑:程序博客网 时间:2024/06/05 04:10

1.5、角色的跳跃

角色的跳跃,事实上是对velocity.y进行更改。

准备好跳跃的动作:

 

 

在改变velocity.y的同时再渲染这个动作就可以完成角色的普通跳跃了。但是注意能跳上去就应该能落下来,因此需要给角色添加一个重力因素,让velocity.y根据时间递减掉该因素,就相当于重力的影响而让角色下落了。

 

这里,要考虑到角色在什么条件下不再下降。因为你添加了重力之后,角色会不断下落,但最后游戏界面就没有角色了,所以一定要控制好。因此,有两种解决方案,一个是利用角色跳跃的时间,让在这段时间内下落,这样做首先你要知道跳跃时间。而另一种方法是给角色的下落添加条件:

controller.isgrounded表示对象是否与其他对象发生碰撞。可以用这个方法表示当角色与地面发生碰撞时就停止下落。

 

添加了跳跃之后,对原代码做了如下修改:

 

 

public class PlayerController : MonoBehaviour 

{

public float gravity;//重力

public float moveSpeed;//移动速度

public float jumpSpeed;//跳跃速度

bool changeDirection = false;//改变移动方向

public Material runMaterial;

public Material idleMaterial;

public Material jumpMaterial;

public Vector3 velocity = Vector3.zero;

private bool jumpEnable = false;//是否处于跳跃状态

private CharacterController controller;

AniSprite aniplay;

// Use this for initialization

void Start () 

{

aniplay = GetComponent("AniSprite"as AniSprite;

controller = GetComponent<CharacterController>();

}

public bool IsFinished = false;//是否完成游戏

public bool IsAlive = true;//角色是否存活

void Update () 

{

if (IsAlive && controller.isGrounded && !IsFinished)//isGrounded对象与任何带碰撞的物体且法线方向在攀爬角度以内为true

{

velocity = new Vector3(Input.GetAxis("Horizontal"), 00);

jumpEnable = false;//只有按下跳跃时才为true

if (velocity.x == 0)//站立姿势

{

transform.renderer.material = idleMaterial;//改变材质

aniplay.aniSprite(11true);

}

if (velocity.x < 0)//向左

{

transform.renderer.material = runMaterial;

aniplay.aniSprite(1010true);//第二个参数是图像的更换速度,第一个参数是图像拥有多少个精灵

velocity *= moveSpeed;

}

if (velocity.x > 0)

{

transform.renderer.material = runMaterial;

aniplay.aniSprite(1010false);

velocity *= moveSpeed;

}

if (Input.GetButtonDown("Jump"))

{

velocity.y = jumpSpeed;//角色y轴位移发生变法

jumpEnable = true;

}

}

if (IsAlive && !controller.isGrounded && !IsFinished)//角色还没有碰到地面,这一段是为了写在角色跳跃时的左右移动

{

velocity.x = Input.GetAxis("Horizontal");

if (changeDirection == false)//向右

{

if (jumpEnable)

{

velocity.x *= moveSpeed;

transform.renderer.material = jumpMaterial;

aniplay.aniSprite(1111true);

}

}

if (changeDirection == true)//向左

{

if (jumpEnable)

{

velocity.x *= moveSpeed;

transform.renderer.material = jumpMaterial;

aniplay.aniSprite(1111false);

}

}

}

if (velocity.x < 0)

changeDirection = false;

if (velocity.x > 0)

changeDirection = true;

velocity.y -= gravity*Time.deltaTime;//重力影响

controller.Move(velocity*Time.deltaTime);//角色控制器的移动函数,传入vector3和deltta时间

}

}

对于controller.isGrounded,必须是两个对象发生碰撞,而碰撞取决于两个对象的胶囊碰撞体,有时候这两个碰撞体初始形态并不如你所愿,因此需要进行修改:

对于Character Controller组件,需要修改的是:

 

Center修改胶囊的位置,Radius修改半径,Height修改高度

对于普通的Box Conllider,修改的是

 

size修改大小

如图,绿色部分即为碰撞体。

 

0 0