我只想在按下 space 键时在 y 轴上移动游戏对象

I want to move the Gameobject on y-axis only when I hit space key

想法是让物体像直升机一样从地面上升起。 我通过将 transform.position.y 保存到 y 变量中来解决这个问题,但是当我使用 transfrom.translate 更改其位置时它显示错误。 这是我正在使用的代码。请帮助

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement: MonoBehaviour
{
[SerializeField] private float _speed = 5;

void Start()
{
    transform.position = new Vector3(0, 0, 0);
}

void Update()
{
    Movement();
}
public void Movement()
{
    float y = transform.position.y;
    float horizontalInput = Input.GetAxis("Horizontal");
    float HorizontalInput = horizontalInput * _speed * Time.deltaTime;
    float verticalInput = Input.GetAxis("Vertical");
    float VerticalInput = verticalInput * _speed * Time.deltaTime;

    transform.position = transform.position + new Vector3(HorizontalInput, y, VerticalInput);
    if(Input.GetKey(KeyCode.Space))
    {
        y = transform.Translate(Vector3.up * _speed * Time.deltaTime);
        y++;
    }
}}

看起来您可能对 Transform.Translate 的作用感到困惑,因为它没有 return 任何值,就像您的代码建议的那样。


这里有两种不同的用法:

使用向量:

public void Translate(Vector3 translation);

Moves the transform in the direction and distance of translation.

使用 x,y,z:

public void Translate(float x, float y, float z);

Moves the transform by x along the x axis, y along the y axis, and z along the z axis.

来自: https://docs.unity3d.com/ScriptReference/Transform.Translate.html


这是修复代码的一种方法。

public void Movement()
{
    float x = Input.GetAxis("Horizontal") * _speed * Time.deltaTime;
    float y = 0;
    float z = Input.GetAxis("Vertical") * _speed * Time.deltaTime;

    if(Input.GetKey(KeyCode.Space))
    {
        y += _speed * Time.deltaTime;
    }

    transform.position += new Vector3(x, y, z);

    // or use:
    // transform.Translate(x, y, z);

    // or use:
    // transform.Translate(new Vector3(x, y, z));
}