C# 我只想在按下空格键时在y轴上移动游戏对象
这个想法是让物体像直升机一样从地面上升。 我通过将transform.position.y保存为y变量来解决这个问题,但在使用transfrom.translate更改其位置时显示错误。 这是我正在使用的代码。请帮忙C# 我只想在按下空格键时在y轴上移动游戏对象,c#,unity3d,game-development,C#,Unity3d,Game Development,这个想法是让物体像直升机一样从地面上升。 我通过将transform.position.y保存为y变量来解决这个问题,但在使用transfrom.translate更改其位置时显示错误。 这是我正在使用的代码。请帮忙 using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement: MonoBehaviour { [SerializeField]
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的作用感到困惑,因为它不会返回任何值,就像您的代码所建议的那样
这里有两种不同的用法: 使用向量: 沿
平移的方向和距离移动变换
使用x、y、z:
将变换沿x轴移动x
,沿y轴移动y
,沿z轴移动z
发件人:
这里有一种修复代码的方法
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));
}
public void Translate(float x, float y, float z);
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));
}