我正在Unity上开发一款基础游戏,以提高自己的水平。这是一款基本的无尽跑酷平台游戏。
如果当玩家在地面上时,你点击右键,它就会跳起来;如果不在地面上,它就会落得更快。
但是我想不出如何让玩家在落下时死于抓不住平台。请你检查一下我的代码好吗?我正试图找到一个 "if "命令来实现它。
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerControls : MonoBehaviour
{
public Rigidbody2D rb;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
float CurrentFallTime;
public float MaxFallTime = 7;
bool PlayerIsFalling;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
rb.velocity = new Vector2(5, rb.velocity.y);
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
CurrentFallTime += Time.deltaTime;
if (Input.GetMouseButtonDown(0) && onGround)
{
rb.velocity = new Vector2(rb.velocity.x, 12);
}
if (Input.GetMouseButtonDown(0) && !onGround)
{
rb.velocity = new Vector2(rb.velocity.x, -10);
}
// I want it to die and go to game over screen when it exceeds the CurrentFallTime
if ()
{
if (CurrentFallTime >= MaxFallTime)
{
SceneManager.LoadScene("GameOver");
}
}
}
}
EDIT: 解决了! 我模拟添加了 "if(onGround) "并重置了CurrentFallTime。这是新的代码。
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerControls : MonoBehaviour
{
public Rigidbody2D rb;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
float CurrentFallTime;
public float MaxFallTime = 7;
bool PlayerIsFalling;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
rb.velocity = new Vector2(5, rb.velocity.y);
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
CurrentFallTime += Time.deltaTime;
if (onGround)
{
CurrentFallTime = 0f;
}
if (Input.GetMouseButtonDown(0) && onGround)
{
rb.velocity = new Vector2(rb.velocity.x, 12);
}
if (Input.GetMouseButtonDown(0) && !onGround)
{
rb.velocity = new Vector2(rb.velocity.x, -10);
}
if (CurrentFallTime >= MaxFallTime)
{
SceneManager.LoadScene("GameOver");
}
}
}
这是我现在才想到的,所以不知道效果如何,但你可以创建一个1面的平面碰撞器,并将其定位为跟随玩家的x坐标和y坐标,但要比地面的高度略低,例如1unit。然后检查玩家何时与飞机相撞,如果相撞了,那么你就知道玩家已经坠落了。
所以,创建一个空的GameObject并添加碰撞器,不需要任何网格属性,并将碰撞器触发器设置为true。然后在玩家控制中添加类似于in update的东西。
colliderGo.transform.location = new Vector3(transform.x, groundHeight - 1, transform.z)
同时在玩家控制器的功能中
function onTrigger(Collider col) {
if (col.tag == "fallDetector") {
Debug.Log("What a cruel world")
playHasFallen = true;
}
}
这样的东西应该可以用。