添加2D刚体组件
挂载脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class Move : MonoBehaviour
{
private float horizontal;
private float vertical;
//私有变量暴露到编辑器
[SerializeField]
[Range(0f, 20f)] private float MoveSpeed = 10;//移动速度
[SerializeField]
[Range(0f, 100f)] private float rotateSpeed = 50f;//转动速度
Rigidbody2D rigidbody;
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
float h = Input.GetAxis("Horizontal");//转向
float v = Input.GetAxis("Vertical");//前后
Vector3 moveDirection = transform.up*-1f;//获取当前朝向向量
if (v>=0)
{
transform.Rotate(new Vector3(0, 0, -h) * rotateSpeed * Time.deltaTime); //左右旋转
}
else
{
transform.Rotate(new Vector3(0, 0, h) * rotateSpeed * Time.deltaTime); //倒车时反转控制
}
if (v!=0)
{
rigidbody.AddForce(moveDirection * 10f*v*MoveSpeed);//按键时移动
rigidbody.velocity = Vector2.zero;//消除刚力,否则会一直移动
}
else
{
rigidbody.velocity = Vector2.zero;//消除刚力,否则会一直移动
}
}
}
WS前进后退,AD转向,主要是转向后可以沿着当前朝向的方向移动?
|