目录
2D游戏控制
简单的上下左右移动
第一种 使用Rigidbody2D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
private Rigidbody2D rb;
private float moveH, moveV;
[SerializeField] private float moveSpeed = 5.0f;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
moveH = Input.GetAxis("Horizontal") * moveSpeed;
moveV = Input.GetAxis("Vertical") * moveSpeed;
}
private void FixedUpdate()
{
rb.velocity = new Vector2(moveH, moveV);
}
}
第二种 上下左右移动加上旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public int step; //步长
public float velocity = 0.35f; //速度
private int x;
private int y;
private Vector3 playerPos;
void Start()
{
InvokeRepeating("Move", 0, velocity);
x = 0; y = step;
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
gameObject.transform.loca

这篇博客详细介绍了在Unity中实现2D游戏控制的几种方法,包括简单的Rigidbody2D移动、带有旋转的移动以及2D空战飞机和坦克的移动控制。通过示例代码展示了如何处理键盘输入,实现物体的平移和旋转,适用于创建各种2D游戏场景。
3704

被折叠的 条评论
为什么被折叠?



