在上一篇文章里介绍了两种使物体运动的方式
这篇文章来介绍下鼠标和键盘控制物体的移动。
一、transform下控制物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//键盘控制
//得到水平轴
float h = Input.GetAxis("Horizontal");
//得到垂直轴
float v = Input.GetAxis("Vertical");
//进行变换
transform.Translate(new Vector3(h, v, 0));
//鼠标控制
float h1 = Input.GetAxis("Mouse X");
float v1 = Input.GetAxis("Mouse Y");
transform.Translate(new Vector3(h1, v1, 0));
}
}
键盘控制演示:
鼠标控制演示:
二、刚体组件下控制物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ball : MonoBehaviour {
private Rigidbody rd; //创建一个刚体
// Use this for initialization
void Start () {
rd = GetComponent<Rigidbody>(); //得到当前游戏物体的刚体组件
}
// Update is called once per frame
void Update () {
//键盘控制
//水平移动(左右)
float h=Input.GetAxis("Horizontal");
//垂直移动(前后)
float v = Input.GetAxis("Vertical");
//给刚体一个力,可以使游戏物体前后左右移动
rd.AddForce(new Vector3(h, 0, v));
//鼠标控制
float h1 = Input.GetAxis("Mouse X");
float v1 = Input.GetAxis("Mouse Y");
rd.AddForce(new Vector3(h1, 0, v1));
}
}