一、不添加刚体组件,使物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
private Transform t;
void Start()
{
t = this.GetComponent<Transform>(); //获取本身和所有子子物体
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
t.Translate(Vector3.forward * Time.deltaTime * 6, Space.World);
}
if (Input.GetKey(KeyCode.S))
{
t.Translate(Vector3.back * Time.deltaTime * 6, Space.World);
}
if (Input.GetKey(KeyCode.A))
{
t.Translate(Vector3.left * Time.deltaTime * 6, Space.World);
}
if (Input.GetKey(KeyCode.D))
{
t.Translate(Vector3.right * Time.deltaTime * 6, Space.World);
}
}
}
1.首先,我们通过t = this.GetComponent<Transform>() 获取物体本身的坐标。
2.然后通过Translate()这个方法可以使得物体移动,里面有Vector3,
(Vector3是一个三维向量,在unity中用于传递3D位置和方向),通过在后面加入Time.deltaTime来使得物体移动更加的平滑。
3.里面还有一个Space.World,代表着是以世界坐标系来移动的,与之相对的还有Space.Self,它代表着以自身坐标系来移动。
二、通过添加刚体,是用MovePosition方法来移动物体
1.首先我们需要给物体添加刚体。
使用这个方法,物体移动时就不会穿透其他的物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
//创建一个私有的Rigidbody和Transform,用于接收Rigidbody和Transform的组件
private Rigidbody m_rigidbody;
private Transform m_transform;
void Start()
{
//拿到Rigidbody和Transform的组件
m_rigidbody = this.GetComponent<Rigidbody>();//刚体组件是用来移动物体
m_transform = this.GetComponent<Transform>();//使用Transform的组件是因为我们采用的movePosition方法是用改变Transform来移动的
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
m_rigidbody.MovePosition(m_transform.position + Vector3.forward * 0.05f);
}
if (Input.GetKey(KeyCode.S))
{
m_rigidbody.MovePosition(m_transform.position + Vector3.back * 0.05f);
}
if (Input.GetKey(KeyCode.A))
{
m_rigidbody.MovePosition(m_transform.position + Vector3.left * 0.05f);
}
if (Input.GetKey(KeyCode.D))
{
m_rigidbody.MovePosition(m_transform.position + Vector3.right * 0.05f);
}
}
}
三、用addforce方法来移动物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
//创建一个私有的Rigidbody用于接收Rigidbody
private Rigidbody m_rigidbody;
void Start()
{
m_rigidbody = this.GetComponent<Rigidbody>(); //拿到Rigidbody组件
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
m_rigidbody.AddRelativeForce(Vector3.forward*30, ForceMode.Force);//这个是以物体自身坐标系来移动
m_rigidbody.AddForce(Vector3.forward*30, ForceMode.Force);//这个是以世界坐标系来移动
}
if (Input.GetKey(KeyCode.S))
{
m_rigidbody.AddForce(Vector3.back*30, ForceMode.Force);
}
if (Input.GetKey(KeyCode.A))
{
m_rigidbody.AddForce(Vector3.left*30, ForceMode.Force);
}
if (Input.GetKey(KeyCode.D))
{
m_rigidbody.AddForce(Vector3.right*30, ForceMode.Force);
}
}
}
ForceMode 是一个枚举结构,里面有:
ForceMode.Force 是给物体添加一个作用力来使物体移动。
ForceMode.Acceleration 表示添加一个可持续加速度到刚体,会忽略它的质量。
ForceMode.Impulse 表示添加一个瞬间冲击力到刚体,会使用它的质量。