您的位置:首页 > 移动开发 > Unity3D

使用方向键和awsd来分别控制Unity3D中的物体

2020-07-20 18:25 441 查看

假设是坦克物体,生成脚本TankMovement,在其中完成以下内容后调整修改Edit>Project setting>Input中的内容即可

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class TankMovement : MonoBehaviour

{

    public float speed = 15;//1.定义速度为15米每秒

    public float angularSpeed = 20;//8.坦克的旋转角度是20度每秒

    //public float number = 1;//5.5)1.设置两个坦克编号(自己加的不知道对不对)

    private Rigidbody rigidbody;//3.使用刚体组件为其添加一个速度--创建刚体组件

    public CtrlType ctrlType;

    public float v, h;

    void Start()

    {

        rigidbody = GetComponent<Rigidbody>();//4.在这里获得刚体组件

    }

    private void FixedUpdate()

    {

        switch(ctrlType)

        {

            case CtrlType.One:

                v = Input.GetAxis("Vertical");

                h = Input.GetAxis("Horizontal");

                break;

            case CtrlType.Two:

                v = Input.GetAxis("Vertical1");

                h = Input.GetAxis("Horizontal1");

                break;

        }

        //float v = Input.GetAxis("VerticalPlayer" + number);

        rigidbody.velocity = transform.forward * v * speed;

        //float h = Input.GetAxis("HorizontalPlayer" + number);

        rigidbody.angularVelocity = transform.up * h * angularSpeed;

    }

}

public enum CtrlType

{

    One,

    Two

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: