梁隽哲 2019-03-15 22:17 采纳率: 0%
浏览 794

unity3d 为什么按w 物体向左运动啊

图片说明
物体和相机都对准了z轴

代码换过两个还不行

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

public class TankController : MonoBehaviour
{
Rigidbody rigidBody;

public float moveForce ;

public float maxSpeed ;

public float rotForce = 100f;

public float rotSpeed ;

// Start is called before the first frame update
void Start()
{
    rigidBody = GetComponent<Rigidbody> ();
    moveForce = 500f;
    maxSpeed = 10f;
    rotSpeed = 90f;
}


// Update is called once per frame

void Update(){
//print ("Update" + Time.deltaTime);
//运动
Move ();
}

//运动函数
void Move(){
    //监听键盘的输入
    //KeyCode表示键码值
    if (Input.GetKey (KeyCode.W)) {
        //让坦克向前移动:①改变坐标②给某个物体的钢体添加力(被选用)
        //transform.forward 表示坦克的正前方也就是Z轴的正方向
        rigidBody.AddForce(moveForce * transform.forward);
        //transform.right x轴的正前方
        //transform.up Y轴的正前方
    }

    //      if(Input.GetKey(KeyCode.A)){
    //          rigidBody.AddForce (moveForce * (-transform.right));
    //      }
    if(Input.GetKey(KeyCode.S)){
        rigidBody.AddForce (moveForce * (-transform.forward));
    }


    //限速 magnitude 大小 表示速度的绝对值
    if(rigidBody.velocity.magnitude > maxSpeed){
        //rigidBody.velocity.Normalize 速度的方向
        //Normalize  标准化,理解为单位值(单位向量)
        rigidBody.velocity = maxSpeed * rigidBody.velocity.normalized;
    }

    //旋转
    if(Input.GetKey(KeyCode.A)){
        //添加旋转力
        //rigidBody.AddTorque(rotForce * transform.up); 一会儿快,一会儿慢
        //更改旋转角度实现坦克转向 (为什么上一帧到这一帧欧拉角会改变)
        //定义变量,表示这一帧应该指向的角度 = 上一帧的角度 + 这一帧改变的角度
        //localEulerAngles 物体自身的欧拉角
        //Time.deltaTime  表示当前这一帧所经历的时间
        var angle = transform.localEulerAngles + rotSpeed * Time.deltaTime * -transform.up ;
        //print (Time.deltaTime);
        //设置坦克的旋转角度
        //Quaternion.Euler()  将欧拉角转化为四元数,返回一个4元角度 
        rigidBody.MoveRotation (Quaternion.Euler (angle));
    }
    //向右旋转
    if(Input.GetKey(KeyCode.D)){
        var angle = transform.localEulerAngles + rotSpeed * Time.deltaTime * transform.up;
        rigidBody.MoveRotation (Quaternion.Euler (angle));}
   }

}

  • 写回答

2条回答 默认 最新

  • 混沌太初 2019-03-16 12:08
    关注

    很简单啊,你的内置方法调用错误了

    评论

报告相同问题?

悬赏问题

  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?