小白学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);
    }

}

使用方法:

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

相关推荐
Martina_032117 小时前
AI生成3D场景导入 Unity/Unreal 后,NPC 总串层?用6步检查导航高度与跨层连接
人工智能·游戏·数学建模·3d·unity·自然语言处理·aigc
Nil20817 小时前
leetcode 55跳跃游戏
算法·leetcode·游戏
小贺儿开发19 小时前
Unity 局域网遥控幻灯片展示工具 3.0
科技·http·unity·工具·ppt·通信·网页
Nil20820 小时前
leetcode 45跳跃游戏Ⅱ
算法·leetcode·游戏
外收内放2 天前
Python基础语法练习题(拓展1)
python·游戏
Martina_03212 天前
AI生成的过山车轨道导入后频繁脱轨?用5步检查样条、轨距与碰撞
图像处理·人工智能·游戏·3d·材质·游戏策划·关卡设计
Martina_03212 天前
AI生成的模块场景一烘焙就有黑边?用6步检查Lightmap UV、纹素密度与Padding
人工智能·游戏·3d·aigc·uv·游戏策划·关卡设计
狂野小白兔2 天前
AI游戏制作04——Codex 搭配 Godot MCP 全流程教程
人工智能·游戏·godot
狂野小白兔2 天前
AI游戏制作00——AI制作游戏需要准备的前置条件
人工智能·游戏
Martina_03212 天前
AI生成的盔甲换动作后漂移?用6步检查挂点、骨架映射与 Bind Pose
人工智能·游戏·3d·ai·自然语言处理·aigc·游戏策划