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);
        }        
    }
相关推荐
星辰徐哥12 小时前
Unity基础:游戏对象的激活与隐藏:SetActive方法详解
游戏·unity·lucene
CS创新实验室13 小时前
CS实验室行业报告:游戏行业就业分析报告
大数据·游戏
王杨游戏养站系统13 小时前
王杨游戏蜘蛛养站系统:提交百度站长工具平台教程!
游戏·百度·游戏下载站养站系统·游戏养站系统
码界筑梦坊14 小时前
112-基于Flask的游戏行业销售数据可视化分析系统
开发语言·python·游戏·信息可视化·flask·毕业设计·echarts
maaath14 小时前
【maaath】Flutter for OpenHarmony 游戏中心应用实战开发
flutter·游戏·华为·harmonyos
阿斯加德D14 小时前
植物大战僵尸拼接版下载2026最新版完整及游戏内容详解
游戏
源码老李1 天前
独立游戏AI音乐指南:用Suno AI让游戏拥有灵魂
人工智能·游戏·ai编程
_守一1 天前
UE DS+Nakama进行游戏服务器开发(1)源码编译nakama
服务器·游戏
魔士于安1 天前
Unity 超市总动员 超市收银台 超市货架 超市购物手推车 超市常见商品
游戏·unity·游戏引擎·贴图·模型
zh路西法1 天前
【Unity实现Oneshot胶卷显形】游戏窗口化与Win32API的使用
游戏·unity·游戏引擎