Unity制作“见缝插针”小游戏

本文介绍了一个使用Unity进行游戏开发的示例,包括控制物体旋转、针头碰撞检测、针的运动控制及游戏管理等核心功能的实现方法。
控制小球旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateSelf : MonoBehaviour {
    //每秒旋转90度
    public float speed = 90;

    // Update is called once per frame
    void Update () {
     //绕Z轴顺针旋转
        transform.Rotate(new Vector3(0, 0, -speed * Time.deltaTime));
    }
}

这里写图片描述

针头碰撞检测
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PinHead : MonoBehaviour {

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "PinHead")
        {
            GameObject.Find("GameManager").GetComponent<GameManager>().GameOver();
        }
    }
}
控制针的运动位置
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pin : MonoBehaviour {

    public float speed = 5;
    private bool isFly = false;
    private bool isReach = false;
    private Transform startPoint;
    private Vector3 targetCirclePos;
    private Transform circle;

    // Use this for initialization
    void Start () {
        startPoint = GameObject.Find("StartPoint").transform;
        circle = GameObject.FindGameObjectWithTag("Circle").transform;
        targetCirclePos = circle.position;
        targetCirclePos.y -= 1.55f;
    }

    // Update is called once per frame
    void Update () {
        if (isFly == false)
        {
            if (isReach == false)
            {
                transform.position = Vector3.MoveTowards(transform.position, startPoint.position, speed * Time.deltaTime);
                if (Vector3.Distance(transform.position, startPoint.position) < 0.05f)
                {
                    isReach = true;
                }
            }
        }
        else
        {
            transform.position = Vector3.MoveTowards(transform.position, targetCirclePos, speed * Time.deltaTime);
            if(Vector3.Distance( transform.position,targetCirclePos) < 0.05f)
            {
                transform.position = targetCirclePos;
                transform.parent = circle;
                isFly = false;
            }
        }
    }

    public void StartFly()
    {
        isFly = true;
        isReach = true;
    }
}
游戏管理
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {

    private Transform startPoint;
    private Transform spawnPoint;
    private Pin currentPin;
    private bool isGameOver = false;
    private int score = 0;
    private Camera mainCamera;
    public Text scoreText;
    public GameObject pinPrefab;
    public float speed = 3;

    // Use this for initialization
    void Start () {
        startPoint = GameObject.Find("StartPoint").transform;
        spawnPoint = GameObject.Find("SpawnPoint").transform;
        mainCamera = Camera.main;
        SpawnPin();
    }

    private void Update()
    {
        if (isGameOver) return;
        if (Input.GetMouseButtonDown(0))
        {
            score++;
            scoreText.text = score.ToString();
            currentPin.StartFly();
            SpawnPin();
        }
    }

    void SpawnPin()
    {
         //针的实例化
        currentPin = GameObject.Instantiate(pinPrefab, spawnPoint.position, pinPrefab.transform.rotation).GetComponent<Pin>();
    }

    public void GameOver()
    {
        if (isGameOver) return;
        GameObject.Find("Circle").GetComponent<RotateSelf>().enabled = false;
        StartCoroutine(GameOverAnimation());
        isGameOver = true;
    }

    IEnumerator GameOverAnimation()
    {
        while (true)
        {
            mainCamera.backgroundColor = Color.Lerp(mainCamera.backgroundColor, Color.red, speed * Time.deltaTime);
            mainCamera.orthographicSize = Mathf.Lerp(mainCamera.orthographicSize, 4, speed * Time.deltaTime);
            if( Mathf.Abs( mainCamera.orthographicSize-4 )<0.01f)
            {
                break;
            }
            yield return 0;
        }
        yield return new WaitForSeconds(0.2f);
        //重新加载场景
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
游戏初始状态和运行结果

这里写图片描述
这里写图片描述

### 关于免费 Unity 2D 格斗射击游戏源码 对于寻找免费的 Unity 2D 格斗射击游戏源码,可以考虑访问一些开源平台或社区资源。GitHub 是一个很好的起点,在那里开发者们分享各种类型的项目,包括游戏开发相关的资源。 #### GitHub 上查找资源的方法 可以通过关键词搜索来找到合适的项目。例如,“Unity 2D Fighting Shooting Game”,这可能会返回多个符合条件的结果。浏览这些项目的描述和评论区可以帮助判断其质量和适用性[^1]。 另外,Asset Store 中也有一些标记为“Free”的资产包可能含有类似的代码片段或是完整的模板,尽管不是所有的都是完全公开源码的形式提供给用户修改使用的。 为了更具体地帮助定位到这样的资源,下面是一个简单的 Python 脚本用于自动化查询 GitHub API 并获取相关仓库的信息: ```python import requests def search_github_repos(query): url = f"https://api.github.com/search/repositories?q={query}&sort=stars&order=desc" response = requests.get(url) if response.status_code == 200: data = response.json() repos = [] for item in data['items']: repo_info = { 'name': item['full_name'], 'description': item['description'] or "No description provided", 'url': item['html_url'] } repos.append(repo_info) return repos[:5] # 返回前五个最匹配的仓库 else: print(f"Failed to fetch data from GitHub, status code {response.status_code}") return [] search_query = "Unity 2D Fighting Shooting Game free" results = search_github_repos(search_query) for idx, result in enumerate(results, start=1): print(f"{idx}. Name: {result['name']}\n Description: {result['description']}\n URL: {result['url']}\n") ``` 此脚本会按照星数排序并打印出与指定主题最接近的五个公共存储库链接及其简介。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值