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

}

使用方法:

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

相关推荐
superior tigre7 小时前
45 跳跃游戏2
算法·leetcode·游戏
CyL_Cly8 小时前
杀戮尖塔2mod:二次元猎宝
windows·游戏
cxr82810 小时前
从细胞到蜂群:基于康威生命游戏原理的多智能体编排
游戏
小辉同志10 小时前
45. 跳跃游戏 II
c++·leetcode·游戏·贪心算法
开开心心就好11 小时前
避免借电脑尴尬的故障模拟工具
科技·游戏·visualstudio·edge·pdf·电脑·powerpoint
XiaoZhangGOGOGO12 小时前
《剑来2》动画第二季点映百度网盘提取码_百度网盘提取码资源
unity
深念Y12 小时前
王者荣耀与英雄联盟数值设计对比:穿透、乘算与加算、增伤乘算更厉害,减伤加算更厉害
数学·算法·游戏·建模·游戏策划·moba·数值
惊鸿醉12 小时前
基于Kinect SDK的Unity艺术交互展项——完整技术方案
unity
聊点儿技术13 小时前
海外玩家伪装来源? 怎么用IP归属地识别
网络·tcp/ip·游戏·游戏安全·ip地址查询·查ip归属地·海外玩家
Swift社区13 小时前
如何让鸿蒙游戏在多设备之间“实时同步状态”?
游戏·华为·harmonyos