zoukankan      html  css  js  c++  java
  • unity中利用纯物理工具制作角色移动跳跃功能

    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;
    }
    }
    }
    }

  • 相关阅读:
    js实现倒数 —— ‘剩下多少天多少秒’
    CSS单位,em,rem以及元素的宽度和高度
    基于原生JS+node.js+mysql打造的简易前后端分离用户登录系统
    隐藏微信小程序剪贴板提示
    微信小程序实现多选分享
    微信小程序开发过程中出现问题及解答
    Visual Studio Code 使用指南
    openLayers 4 canvas图例绘制,canvas循环添加图片,解决图片闪烁问题
    微信小程序个人/企业开放服务类目一览表
    微信小程序日常开发中常遇到的错误代码
  • 原文地址:https://www.cnblogs.com/xiaoahui/p/9976869.html
Copyright © 2011-2022 走看看