小白学Unity03-太空漫游游戏脚本,控制飞船移动旋转

首先搭建好太阳系以及飞机的场景

需要用到3个脚本

1.控制飞机移动旋转

2.控制摄像机LookAt朝向飞机和差值平滑跟踪飞机

3.控制各个星球自转以及围绕太阳旋转(rotate()和RotateAround())

=============================================

1.控制飞机移动旋转的脚本

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovePlan : MonoBehaviour
{
    // 这个脚本是用户用WASD键盘控制飞机移动

    public float MoveSpeed = 0.5f;
    public float RotateSpeed = 2f;
    float mOUSESPEED;

    void Update()
    {

        if (Input.GetKey(KeyCode.W))
        {
            this.transform.Translate(new Vector3(0, 0, 1 * MoveSpeed * Time.deltaTime));
        }
        if (Input.GetKey(KeyCode.S))
        {
            this.transform.Translate(new Vector3(0, 0, -1 * MoveSpeed * Time.deltaTime));
        }
        if (Input.GetKey(KeyCode.A))
        {
            this.transform.Translate(new Vector3(-1 * MoveSpeed * Time.deltaTime,0, 0 ));
        }
        if (Input.GetKey(KeyCode.D))
        {
            this.transform.Translate(new Vector3(1 * MoveSpeed * Time.deltaTime, 0, 0));
        }
        //控制物体旋转
        mOUSESPEED = Input.GetAxis("Mouse X");
        this.transform.Rotate(new Vector3(0, mOUSESPEED * RotateSpeed*Time.deltaTime, 0));
    }
}

2.控制摄像机LookAt朝向飞机和差值平滑跟踪飞机 的脚本

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ControlCamera : MonoBehaviour
{
    // 这个脚本是用来让摄像机跟踪目标,并且一直看向目标

    public Transform onetarget;//这是飞机的变换组件
    public GameObject OnePoint;
    public float Movespeed = 1f;
    
    void Update()
    {           

        this.transform.position = Vector3.Lerp(this.transform.position, OnePoint.transform.position, Movespeed * Time.deltaTime);

        this.transform.LookAt(onetarget);
    }

}

使用方法:

分别挂在到摄像机和飞机上

相关推荐
KhalilRuan1 小时前
Unity-MMORPG内容笔记-其一
unity·游戏引擎
向宇it5 小时前
【unity游戏开发——网络】网络游戏通信方案——强联网游戏(Socket长连接)、 弱联网游戏(HTTP短连接)
网络·http·游戏·unity·c#·编辑器·游戏引擎
ii_best11 小时前
按键精灵 安卓脚本开发:游戏实战之自动切换账号辅助工具
游戏
切韵10 天前
Unity编辑器扩展:UI绑定复制工具
ui·unity·编辑器
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
D1555408805810 天前
游戏护航小程序源码游戏派单小程序搭建游戏代练小程序源码
游戏
10 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
深空数字孪生10 天前
2025年小程序地图打车的5大技术革新:实时路况预测与智能调度升级
大数据·人工智能·unity·性能优化·小程序·游戏引擎
旧物有情11 天前
Unity2D 街机风太空射击游戏 学习记录 #12QFramework引入
学习·游戏
程序猿多布11 天前
Unity Addressable使用之检测更新流程
unity·addressable