unity_控制物体移动代码

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

目录

2D游戏控制

简单的上下左右移动

第一种 使用Rigidbody2D 

第二种 上下左右移动加上旋转

2D空战飞机的移动

汽车、坦克等移动

坦克的控制


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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值