带图问题:
图中有2种状态 1:跳跃前的玩家 2:跳跃后的玩家 我没有画它但是玩家回到了地面 我的问题是我如何计算图像中的x?
仅问题文本:
我有我创建的这个运动代码我想检查玩家跳跃需要多少时间,跳跃后回到地面以及总时间我该如何计算并打印出来?此外,如果播放器跳跃会影响我想知道的任何事情,则设置播放动画
这是我目前用于跳跃和整体运动的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody rb;
public float MouseSensitivity;
public float MoveSpeed;
public float JumpHeight = 40;
public float TimeToJumpApex = 2;
public float fallMultiplayer = 2.0f;
// Smoothing factors
public float moveSmoothing = 0.1f;
public float rotateSmoothing = 0.1f;
//animator
public Animator anim;
bool isJumping = false;
//
private Vector3 targetMoveDirection;
private Quaternion targetRotation;
// Variables for calculating jump physics
float gravity;
float jumpVelocity;
void Start()
{
//Cursor.visible = false;
}
void Update()
{
// Calculate gravity and jump velocity
gravity = -(2 * JumpHeight) / Mathf.Pow(TimeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * TimeToJumpApex;
anim.SetBool("jump",false);
//Look around
Quaternion rotationDelta = Quaternion.Euler(new Vector3(0, Input.GetAxis("Mouse X") * MouseSensitivity, 0));
targetRotation = rb.rotation * rotationDelta;
rb.MoveRotation(Quaternion.Lerp(rb.rotation, targetRotation, rotateSmoothing));
//vertical parameter
anim.SetFloat("vertical moving", Input.GetAxis("Vertical"));
anim.SetFloat("horizontal", Input.GetAxis("Horizontal"));
//Move
targetMoveDirection = transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal");
rb.AddForce(targetMoveDirection * MoveSpeed, ForceMode.VelocityChange);
rb.velocity = Vector3.Lerp(rb.velocity, Vector3.zero, moveSmoothing);
//Jump
if (anim.GetCurrentAnimatorStateInfo(0).IsName("Jump"))
{
isJumping = true;
}
else
{
isJumping = false;
}
if (Input.GetKeyDown(KeyCode.Space) && Mathf.Abs(rb.velocity.y) < 0.01f && !isJumping)
{
anim.SetBool("jump",true);
rb.velocity = new Vector3(rb.velocity.x, jumpVelocity, rb.velocity.z);
}
}
private void FixedUpdate()
{
if (rb.velocity.y < 0)
{
rb.velocity += Vector3.up * gravity * fallMultiplayer * Time.deltaTime;
}
else if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.Space))
{
rb.velocity += Vector3.up * gravity * fallMultiplayer * Time.deltaTime;
}
}
}
为此,您必须将时间设置为两个时刻:跳跃发生的第一时刻,以及玩家触地的时刻。
private float jumpTime;
private float landTime;
将这些变量添加到代码的顶部。然后,在跳跃部分:
...
else
{
isJumping = false;
}
if (Input.GetKeyDown(KeyCode.Space) && Mathf.Abs(rb.velocity.y) < 0.01f && !isJumping)
{
anim.SetBool("jump",true);
rb.velocity = new Vector3(rb.velocity.x, jumpVelocity, rb.velocity.z);
jumpTime = Time.time; // Add this
}
最后,您需要
OnCollisionEnter
来检测玩家何时停飞:
private void OnCollisionEnter (Collision collision)
{
if (collision.gameObject.tag == "Ground" || collision.gameObject.name == "Ground") // Or anything else to check if the collision object is ground
{
landTime = Time.time;
float totalTime = landTime - jumpTime; // This is what you're looking for in seconds
Debug.Log (totalTime);
}
}
希望对您有所帮助:)