zoukankan      html  css  js  c++  java
  • unity

    在unity实现跳跃的时候按下时间越长,跳跃高度越高的功能

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class PlayerControl : MonoBehaviour
    {
        private Rigidbody2D rb;
        private Animator animator;
        public float speed = 10;
        public bool isGround,isJump;
        public Transform groundCheck;
        public LayerMask ground;
        public float jumpForce = 30;
        public float jumpTime,jumpTimeCounter;
    
        void Start()
        {
            rb = GetComponent();
            animator = GetComponent();
        }
        void Update()
        {
            float x = Input.GetAxisRaw("Horizontal");
            float y = Input.GetAxis("Vertical");
            if(x != 0)
                transform.localScale = new Vector3(x, 1 ,1);
            Vector2 dir = new Vector2(x,y);
            MoveMent(dir);
    
            //如果按下jump并且人物此时在地面,就可以跳跃
            if(Input.GetButtonDown("Jump") && isGround){
                isJump = true;
                jumpTimeCounter = jumpTime;
                Jump();
            }
            //跳跃持续增高
            if(Input.GetKey(KeyCode.Space) && isJump ){
                if(jumpTimeCounter>0){
                    rb.velocity = new Vector2(rb.velocity.x,0);
                    rb.velocity += Vector2.up * jumpForce;
                    jumpTimeCounter -= Time.deltaTime;
                }
                else {
                    isJump = false;
                }
            }
            if(Input.GetKeyUp(KeyCode.Space))
                isJump = false;
        }
        //判断是否在地面
        void FixedUpdate() {
            isGround = Physics2D.OverlapCircle(groundCheck.position,0.3f,ground);
        }
        void MoveMent(Vector2 dir)
        {
            //地面移动
            rb.velocity = new Vector2(dir.x*speed , rb.velocity.y);
            //rb.velocity = Vector2.Lerp(rb.velocity , (new Vector2(dir.x*speed , rb.velocity.y)) , Time.deltaTime);
        }
        //正常跳跃
        void Jump()
        {
            rb.velocity = new Vector2(rb.velocity.x,0);
            rb.velocity += Vector2.up * jumpForce;
        }
    }
  • 相关阅读:
    Java虚拟机:十七、互斥同步、锁优化及synchronized和volatile
    Java虚拟机:十六、Java内存模型
    Java虚拟机:十五、运行期优化
    Java虚拟机:十三、Java类加载机制
    Java虚拟机:十四、类加载器
    Java虚拟机:十二、虚拟机性能监控与故障处理工具
    字符集
    发布订阅、事务和脚本
    HyperLogLog和GEO
    Redis 的数据结构
  • 原文地址:https://www.cnblogs.com/blowhail/p/13775307.html
Copyright © 2011-2022 走看看