【问题标题】:I want to move the Gameobject on y-axis only when I hit space key我只想在按下空格键时在 y 轴上移动游戏对象
【发布时间】:2020-06-10 08:31:06
【问题描述】:

这个想法是让物体像直升机一样从地面上升。 我通过将 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 game-development


    【解决方案1】:

    您似乎对 Transform.Translate 的作用感到困惑,因为它不返回任何值,就像您的代码所暗示的那样。


    这里有两种不同的用法:

    使用向量:

    public void Translate(Vector3 translation);
    

    translation的方向和距离上移动变换。

    使用 x,y,z:

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

    将变换沿 x 轴移动 x,沿 y 轴移动 y,沿 z 轴移动 z

    来自: 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));
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      相关资源
      最近更新 更多