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

}

使用方法:

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

相关推荐
i橡皮擦20 小时前
TheIsle恐龙岛游戏管理员命令
游戏·恐龙岛·theisle
在路上看风景1 天前
1.2 Unity资源分类
unity·游戏引擎
one named slash1 天前
BMFont在Unity中生成艺术字
unity·游戏引擎
zhutoutoutousan1 天前
氛围数学学习:用游戏化思维征服抽象数学
学习·算法·游戏
郝学胜-神的一滴1 天前
图形学中的纹理映射问题:摩尔纹与毛刺的深度解析
c++·程序人生·unity·游戏引擎·图形渲染·unreal engine
在路上看风景1 天前
10. CPU-GPU协作渲染
unity
程序员agions1 天前
Unity 游戏开发邪修秘籍:从入门到被策划追杀的艺术
unity·cocoa·lucene
JIes__1 天前
Unity(一)——场景切换、退出游戏、鼠标隐藏锁定...
unity·游戏引擎
上海云盾-小余1 天前
im即时通讯被攻击使用游戏盾高防方案有效解决
网络·网络协议·web安全·游戏·金融·ddos
NIKITAshao1 天前
Unity URP Volume组件详解(笔记)
unity·游戏引擎