我想只有当我按下空格键时,才能在Y轴上移动游戏对象。

问题描述 投票:-1回答:1

我的想法是让对象像直升机一样从地面升起,我的方法是将transform.position.y保存到一个y变量中,但是当我使用transfrom.translate来改变它的位置时,它出现了错误。我的方法是将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++;
    }
}}
c# unity3d unityscript game-development
1个回答
3
投票

看起来你可能搞不清楚什么是真正的 Transform.Translate 因为它不返回任何值,就像你的代码所暗示的那样。


下面是它的两种不同用法。

用一个向量

public void Translate(Vector3 translation);

将变换的方向和距离都移到... translation.

使用x,y,z。

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

用x,y,z来移动变换 x 沿X轴。y 沿y轴,和 z 沿着z轴。

来自https:/docs.unity3d.comScriptReferenceTransform.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));
}
© www.soinside.com 2019 - 2024. All rights reserved.