實現跳躍的3種方法:
1、使用rigibody2d組件實現模擬重力,調用addforce()方法或直接給物體一個豎直方向的速度。
代碼如下:(與跳躍無關部分已省略)
firstdemo:
void Update() { if (Input.GetButtonDown("Jump")) { jumpKey = true; } } void FixedUpdate() { if (jumpKey && rg.IsTouchingLayers(ground)) //rigibody2d組件方法,檢測物體是否接觸某個layer,layer在inspector中設置 { nextState = stateEnum.jumping; rg.velocity = new Vector2(rg.velocity.x, jumpForce); SwitchStateTo(stateEnum.jumping); AudioManager.instance.JumpAudio(); } jumpKey = false; if (currentState == stateEnum.jumping && rg.velocity.y > 0.01f && !rg.IsTouchingLayers(ground)) { SwitchStateTo(stateEnum.jumping); } }
跳躍物理效果放在fixedUpdate(),判定放在Update()中。
2.使用rigibody2d,但其類型設置為kinematic(剛體運動學),地面設置為trigger,使用OnTriggerEnter2D()檢測碰撞事件
代碼如下:
notagame:
void Update{ #region if (Input.GetButtonDown("Jump")&& CurrentState!=Hero_states.jump) { CurrentState = Hero_states.jump; amControler.SetBool("run", false); amControler.SetBool("stand", false); amControler.SetBool("jump", true); } #endregion } private void LateUpdate() { if (CurrentState ==Hero_states.jump) { jumpHeight += jumpVelocity * Time.deltaTime * jumpSpeed; jumpVelocity = jumpVelocity - 9.8f * Time.deltaTime * jumpSpeed; Vector3 currentPosition = new Vector3(transform.position.x,transform.position.y,transform.position.z); currentPosition.y = jumpHeight; transform.position = currentPosition; } } private void OnTriggerEnter2D(Collider2D collision) { #region if (collision.gameObject.tag == "Ground") { amControler.SetBool("jump", false); if (Input.GetAxisRaw("Horizontal")!=0) { CurrentState = Hero_states.run; amControler.SetBool("run", true); } else { CurrentState = Hero_states.stand; amControler.SetBool("stand", true); } jumpVelocity = 5f; Debug.Log("ground!"); } #endregion }
但是存在角色調到地里面的情況,有待改進。
3.不使用剛體 (可能是最好的解決辦法)使用 Raycast 是一個很好的選擇。
還沒實現,挖個坑。