TLDR;当玩家的游戏对象通过指定的 y 值位置时,我如何启动它的跳跃?
我正在统一设计我的第一款游戏(到目前为止非常有趣!)我需要一些帮助。基本上,玩家在玩鱼,我想添加一个跳跃动作。
问题是鱼只有在水面时才能跳跃(物体的位置有一个 y 值 ~ = 水面的 y 值)。此外,鱼不应该在空中游泳一次,这意味着一旦它跳跃,它必须返回水中(y 值小于水面的位置)。
我想我明白了解决问题背后的逻辑,但是我在将其转换为代码时遇到了麻烦,而且我在网上找不到任何好的参考代码。欢迎任何想法:)
到目前为止我尝试了什么:
我已经添加了一个水对象(带浮力效应器的方形碰撞器),并弄乱了数字,以便鱼在水中时可以游泳,但不能越过水面。我还添加了一个冲刺动作(来自一个非常好的 youtube 教程),所以玩家可以在水中冲刺,也可以“冲刺”出水面,但随后他们会做这个奇怪的降落伞落回水中并在空中进行一些有限的控制......代码如下。
我认为正确的解决方案是定制跳跃动作和动画,否则将玩家的物体限制在水中。但我不确定该怎么做。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class FishScript : MonoBehaviour
{
public Rigidbody2D rb2d;
private Vector2 moveInput;
public float moveSpeed;
public Animator animator;
//dash stuff
public float dashSpeed;
private float activeSpeed;
public float dashLength = 0.1f, dashCooldown = 24f;
private float dashCounter;
private float dashCoolCounter;
// Start is called before the first frame update
void Start()
{
activeSpeed = moveSpeed;
}
// Update is called once per frame
void Update()
{
//setting "Speed" to velocity, to change to swimming animation
animator.SetFloat("Speed", Math.Abs(rb2d.velocity.x + rb2d.velocity.y));
//basic movement
moveInput.x = Input.GetAxisRaw("Horizontal");
moveInput.y = Input.GetAxisRaw("Vertical");
moveInput.Normalize();
rb2d.velocity = moveInput * activeSpeed;
//dash
if (Input.GetKeyDown(KeyCode.Space) == true)
{
if (dashCoolCounter <= 0 && dashCounter <= 0)
{
activeSpeed = dashSpeed;
dashCounter = dashLength;
}
}
if (dashCounter > 0)
{
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
activeSpeed = moveSpeed;
dashCoolCounter = dashCooldown;
}
}
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
}
谢谢!!