经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 游戏设计 » 查看文章
unity中利用纯物理工具制作角色移动跳跃功能
来源:cnblogs  作者:小辉歌  时间:2018/11/19 9:03:16  对本文有异议

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

protected ContactFilter2D contactFilter;
protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);
protected Rigidbody2D rigid2D;
protected Vector2 move;
public float minGroundNormalY = 0.6f;
public bool grounded = false;
//public float jumpForce=20f;
public float jumpSpeed = 5f;
public float horizonForce = 30f;
public Vector2 maxSpeed;

// Use this for initialization
void Start () {
rigid2D = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update () {

//实现跳跃的三种方案
//01,直接添加一个向上的力
//if (grounded && Input.GetKeyDown(KeyCode.Space)) rigid2D.AddForce(Vector2.up * jumpForce);
//02,直接添加一个向上的速度
//if (grounded && Input.GetKeyDown(KeyCode.Space)) rigid2D.velocity=(Vector2.up * jumpSpeed)+Vector2.right*rigid2D.velocity.x;
//03,蓄力实现不同的跳跃高度,这里需要设置跳跃按钮的增量速度
float j = Input.GetAxis("Jump");
if (grounded && (Input.GetButtonUp("Jump")||j>0.99f)) rigid2D.velocity = (Vector2.up * jumpSpeed*j) + Vector2.right * rigid2D.velocity.x;

if ((Mathf.Abs(Input.GetAxis("Horizontal")) > 0.01) && (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))) rigid2D.AddForce(Vector2.right * Mathf.Sign(Input.GetAxis("Horizontal")) * horizonForce);
//设置角色减速
if (grounded && !(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) || Input.GetKeyDown(KeyCode.Space))) rigid2D.drag = 20f;
else rigid2D.drag = 0f;

}

private void FixedUpdate()
{
grounded = false;
CheckGround();
if (Mathf.Abs(rigid2D.velocity.x) > maxSpeed.x) rigid2D.velocity = new Vector2(Mathf.Sign(rigid2D.velocity.x) * maxSpeed.x, rigid2D.velocity.y);
}

//判断是正站在某个物体上
void CheckGround()
{
move = Vector2.down;
int count = rigid2D.Cast(move, contactFilter, hitBuffer, 0.02f);//对碰撞体向下的方向检测是否站在某个物体上,精度由检测的射线数和射线长度决定
hitBufferList.Clear();
for (int i = 0; i < count; i++)
{
hitBufferList.Add(hitBuffer[i]);
}
//如果有一个 射线的碰撞点的法线的y大于minGroundNormalY那么设置grounded为true表示站在了物体上
//这里minGroundNormalY一般设置为1到0.6之间即可决定站的平面的倾斜度
for (int i = 0; i < hitBufferList.Count; i++)
{
Vector2 currentNormal = hitBufferList[i].normal;
if (currentNormal.y > minGroundNormalY)
{
grounded = true;
}
}
}
}

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号