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);
        }        
    }
相关推荐
FairGuard手游加固17 小时前
2026年7月份国产游戏审批信息
游戏
星空露珠1 天前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
中国搜索直付通1 天前
棋牌游戏支付与防沉迷:二级商户如何构建“免疫系统”
游戏
2601_962924761 天前
遗忘之海手游战术家怎么玩 遗忘之海手游战术家玩法攻略
游戏
雅客李1 天前
2026年第三季度云手机实测 游戏多开挂机托管三维度数据公开
游戏·智能手机
xcLeigh1 天前
Unity基础:创建你的第一个游戏物体——Cube、Sphere与基本3D物体
游戏·3d·unity·教程
_Tenk_1 天前
自研开源小工具 SwitchDeck:一键切换分辨率/刷新率/音频输出(附 WinForms 高 DPI 踩坑实录)
游戏·分辨率·cs2·看电影·一键切换·音响耳机音频·州瓦go
天糊土2 天前
CentOS 7.6 YUM源更换完整教程
游戏
德迅云安全-上官2 天前
德迅云安全游戏盾与DDoS高防IP对比:差异、优势及选型指南
tcp/ip·游戏·ddos
丁小未2 天前
Unity 几种常见合批手段的要求
游戏·unity·合批·srpbatcher·动态合批·静态合批