简体   繁体   English

用于移动3D对象的Unity脚本并未完全按计划进行

[英]Unity script to move a 3D object doesn't completely go to plan

I'm new to Unity and Stack Overflow, and was looking for a script that will make an object(like a player), move. 我是Unity和Stack Overflow的新手,并且正在寻找一个可以创建对象(如播放器)的脚本。 I have found a script that works, well, kind of works or went to plan. 我找到了一个有效的脚本,有点工作或者去计划。 When I tested the script out, when ever I pressed forward on the arrow keys, instead of going forward, it will just start jumping. 当我测试脚本时,当我向前按箭头键,而不是前进时,它将开始跳跃。 If I press the down arrow key, the cube(or player) will try to push itself under the ground, and then will fall forever, but the left and right arrow keys are working perfectly fine. 如果我按下向下箭头键,立方体(或玩家)将尝试将自己推到地下,然后将永远掉落,但左右箭头键完全正常。 Please note that this script for now is only for moving the player, and nothing else, just in case you were thinking it was supposed to something else or different. 请注意,此脚本目前仅用于移动播放器,而不是其他任何内容,以防您认为它应该是其他的或不同的。 Here is the code: 这是代码:

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

public class Player : MonoBehaviour {


    public float moveSpeed;

    // Use this for initialization
    void Start()
    {
        moveSpeed = 5f;
    }

    // Update is called once per frame
    void Update()
    {

        transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime, 0f);
    }
}

I hope you find a solution or can find an explanation. 我希望你找到解决方案或找到解释。 Thanks for replies. 谢谢你的回复。 Regards, User:9104031 此致,用户:9104031

Unity uses a coordinates system where Y is up and Z is forward. Unity使用坐标系统,其中Y为向上,Z为向前。

In your code, you are moving your player based on your "Vertical" axis input on the Y axis, which would of course map your UP/DOWN arrow keys to the wrong direction. 在您的代码中,您将根据Y轴上的“垂直”轴输入移动播放器,这当然会将您的向上/向下箭头键映射到错误的方向。

All you have to do is change 你所要做的就是改变

transform.Translate(
    moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime
    , moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime
    , 0f);

to

transform.Translate(
    moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime
    , 0f
    , moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);

If I understand you correctly, I believe this is what you'll want in your update section: 如果我理解正确,我相信这是您在更新部分中所需要的:

transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);

I swapped your Y and Z axis. 我换了Y轴和Z轴。 Hope that's what you were going for! 希望这就是你想要的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM