Roll-A-Ball 游戏

Roll-A-Ball 游戏

1)学习资料

2)核心代码:

功能1:用W A S D控制小球移动的脚本:

新建一个C#脚本叫做sphereControll,添加到 小球身上。

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

public class sphereControll : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, 10));
        }
        if (Input.GetKey(KeyCode.S))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -10));
        }
        if (Input.GetKey(KeyCode.A))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(-10, 0, 0));
        }
        if (Input.GetKey(KeyCode.D))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(10, 0, 0));
        }
        if (Input.GetKey(KeyCode.Space))
        {
            GetComponent<Rigidbody>().AddForce(new Vector3(0, 10, 0));
        }
    }
}

或者:用Input.getAxis控制小球移动的脚本:

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

public class sphereControll : MonoBehaviour
{
    float horizontal;
    float vertical;
    public float speed=10;
    // Update is called once per frame
    void Update()
    {
        horizontal=Input.GetAxis("Horizontal");
        vertical=Input.GetAxis("Vertical");

        GetComponent<Rigidbody>().AddForce(new Vector3(horizontal,0,vertical)*speed);
    }
}

功能2:摄像机跟随脚本,

新建一个C#脚本叫做CameraController.cs,添加到 摄像机身上。

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

public class CameraController : MonoBehaviour
{
    public GameObject player;
    Vector3 offset;

    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    void Update()
    {
        transform.position = player.transform.position + offset;
    }
}

功能3:物块自动旋转

新建脚本,Rotator.cs,挂到要旋转的物体上。

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

public class Rotator : MonoBehaviour
{
    void Update()
    {
        transform.Rotate(new Vector3(15,30,45)*Time.deltaTime);
    }
}

功能4:碰到即消失。

在小球的脚本中,添加以下代码,若碰到了tag是pickup的物体,则销毁该物体

csharp 复制代码
void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "pickup")
        {
            Destroy(other.gameObject);
        }        
    }
相关推荐
ZWZhangYu6 小时前
【实践案例】基于大语言模型的海龟汤游戏
人工智能·游戏·语言模型
脏脏a14 小时前
【C语言篇】“三子棋”
c语言·开发语言·游戏
lin zaixi()1 天前
Unity游戏(Assault空对地打击)开发(2) 基础场景布置
游戏
windwind20001 天前
对游戏宣发的粗浅思考
游戏·职场和发展·创业创新·个人开发·游戏策划
Damon小智1 天前
使用Pygame制作“Flappy Bird”游戏
python·游戏·游戏程序·pygame
lin zaixi()2 天前
Unity游戏(Assault空对地打击)开发(3) 摄像机的控制
游戏
美味小鱼2 天前
实践Rust:编写一个猜数字游戏
开发语言·游戏·rust
疯狂创作者3 天前
Scratch 《像素战场》系列综合游戏:像素战场游戏Ⅰ~Ⅲ 介绍
游戏
Sui_Network3 天前
新集成,Sui 的 Phantom 时代正式开启!
游戏·金融·web3·去中心化·区块链
lin zaixi()6 天前
Unity游戏(Assault空对地打击)开发(1) 创建项目和选择插件
游戏