简体   繁体   English

我的车辆代码有什么问题?

[英]What's wrong with my Vehicle code?

I was trying to create a car in unity using a C# Script, everything seems to be fine, the car rotates left and right, except 1 problem.我试图使用 C# 脚本统一创建一辆汽车,一切似乎都很好,汽车向左和向右旋转,除了 1 个问题。 when I press the forward or backwards keys, the car moves left and right instead of forward and backwards, I can't see anything wrong with my code, here's my code:当我按下前进或后退键时,汽车向左和向右移动而不是向前和向后移动,我看不出我的代码有什么问题,这是我的代码:

using UnityEngine;
using System.Collections;

public class Car : MonoBehaviour {
    private Rigidbody carRigid;
    public int speed;
    public int rotateSpeed;

    // Use this for initialization
    void Start () {
        carRigid = GetComponent<Rigidbody> ();

    }

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

    }
    void FixedUpdate(){
        if (Input.GetButton("Forward")){
            carRigid.AddForce (transform.forward * speed * Time.deltaTime);
}
        if (Input.GetButton("Reverse")){
            carRigid.AddForce (transform.forward * -speed * Time.deltaTime);
        }

        if (Input.GetButton("Left")){
            transform.Rotate (0, rotateSpeed, 0);
        }

        if (Input.GetButton("Right")){
        transform.Rotate (0, rotateSpeed, 0);
        }
    }
}

I've just tested your code in a blank Unity scene, and I think you AddForce() is the culprit!我刚刚在一个空白的 Unity 场景中测试了你的代码,我认为你AddForce()是罪魁祸首!

I used我用了

if (Input.GetKey(KeyCode.W))
{
    transform.position += transform.forward * speed * Time.deltaTime;
}

and this seems to be working great!这似乎很好用!

Your car is moving on another axis which is different than the axis you want.您的汽车正在另一个轴上移动,该轴与您想要的轴不同。 try transform.right / transform.left or transform.up / transform.down .尝试 transform.right / transform.left 或 transform.up / transform.down 。

Maybe it's because you have imported a 3D model which it's local forward is not correct.可能是因为您导入的 3D 模型是本地转发不正确。

You have some choices: 1) Fix it in the 3d modeling program an export it again.您有一些选择:1) 在 3d 建模程序中修复它并再次导出它。

2) Create an empty GameObject and make this the parent of your car. 2) 创建一个空的 GameObject 并使其成为您汽车的父级。 Assign the rigid body and relevant codes to this GameObject and Rotate the car model in it's local space until it's fixed ( 90 degrees I guess).将刚体和相关代码分配给这个游戏对象,并在它的局部空间中旋转汽车模型,直到它固定(我猜是 90 度)。

3) use transform.right or transform.left depending on the rotation of your model. 3)根据模型的旋转使用 transform.right 或 transform.left 。

I personally prefer first choice.我个人更喜欢第一选择。

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

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