Unity|小游戏复刻|见缝插针2(C#)

控制针的运动
  1. 新建一个Pin脚本

  2. 将Pin脚本拖到针Pin的下面

  3. 保存代码

c# 复制代码
using UnityEngine;

public class Pin : MonoBehaviour
{
    public float speed = 5;
    private bool isFly = false;
    private bool isReach = false;
    private Transform startPosition;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
    }

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

    }
}
控制针的插入

Pin.C#

c# 复制代码
using UnityEngine;

public class Pin : MonoBehaviour
{
    public float speed = 5;
    private bool isFly = false;
    private bool isReach = false;
    private Transform startPosition;
    private Transform circle;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        circle = GameObject.Find("Circle").transform;
    }

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

    }

    public void StartFly()
    {
        isFly = true ;
        isReach = true;

    }
}

GameManager.C#

c# 复制代码
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private Transform startPosition;
    private Transform spawnPosition;
    private Pin currentPin;

    public GameObject pinPrefab;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        spawnPosition = GameObject.Find("SpawnPosition").transform;
        SpawnPin();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            currentPin.StartFly();
        }
    }

    void SpawnPin()
    {
        currentPin = GameObject.Instantiate(pinPrefab, spawnPosition.position, pinPrefab.transform.rotation).GetComponent<Pin>();
    }
}
控制针的位置和连续发射
  1. 计算Circle和Pin此时位置的y值,为2和0.46,差为1.54

Pin

c# 复制代码
using UnityEngine;

public class Pin : MonoBehaviour
{
    public float speed = 5;
    private bool isFly = false;
    private bool isReach = false;
    private Transform startPosition;

    private Vector3 targetCirclePos;
    private Transform circle;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        circle = GameObject.Find("Circle").transform;
        targetCirclePos = circle.position;
        targetCirclePos.y -= 1.54f;
    }

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

    }

    public void StartFly()
    {
        isFly = true ;
        isReach = true;

    }
}
使针跟随小球运动

Pin

c# 复制代码
using UnityEngine;

public class Pin : MonoBehaviour
{
    public float speed = 5;
    private bool isFly = false;
    private bool isReach = false;
    private Transform startPosition;

    private Vector3 targetCirclePos;
    private Transform circle;


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        circle = GameObject.Find("Circle").transform;
        targetCirclePos = circle.position;
        targetCirclePos.y -= 1.54f;
    }

    // Update is called once per frame
    void Update()
    {
        if (isFly == false)
        {
            if (isReach == false)
            {
                transform.position = Vector3.MoveTowards(transform.position, startPosition.position, speed * Time.deltaTime) ;
                if (Vector3.Distance(transform.position, startPosition.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;

    }
}
继续生成针

GameManager

c# 复制代码
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private Transform startPosition;
    private Transform spawnPosition;
    private Pin currentPin;

    public GameObject pinPrefab;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        spawnPosition = GameObject.Find("SpawnPosition").transform;
        SpawnPin();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            currentPin.StartFly();
            SpawnPin();
        }
    }

    void SpawnPin()
    {
        currentPin = GameObject.Instantiate(pinPrefab, spawnPosition.position, pinPrefab.transform.rotation).GetComponent<Pin>();
    }
}
针的碰撞和游戏结束
  1. 给Pin的针头添加Circle Collider 2D,勾上触发器,再添加rigidbody 2D,重力设为0

  2. 添加PinHead脚本,将其挂载到PinHead上,给PinHead添加上自己添加的PinHead标签

  3. 进行碰撞检测

    PinHead

c# 复制代码
using UnityEngine;

public class PinHead : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "PinHead")
        {
            GameObject.Find("GameManager").GetComponent<GameManager>().GameOver();
        }
    }
}

GameManager

c# 复制代码
using UnityEngine;
using UnityEngine.UIElements;

public class GameManager : MonoBehaviour
{
    private Transform startPosition;
    private Transform spawnPosition;
    private Pin currentPin;
    private bool isGameOver = false;

    public GameObject pinPrefab;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        spawnPosition = GameObject.Find("SpawnPosition").transform;
        SpawnPin();
    }

    // Update is called once per frame
    void Update()
    {
        if (isGameOver) return;
        if (Input.GetMouseButtonDown(0))
        {
            currentPin.StartFly();
            SpawnPin();
        }
    }

    void SpawnPin()
    {
        currentPin = GameObject.Instantiate(pinPrefab, spawnPosition.position, pinPrefab.transform.rotation).GetComponent<Pin>();
    }

    public void GameOver()
    {
        if (isGameOver) return;

        GameObject.Find("Circle").GetComponent<RotateSelf>().enabled = false;

        isGameOver = true;
    }
}
分数增加

GameManager

c# 复制代码
using UnityEditor.Tilemaps;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using TMPro;

public class GameManager : MonoBehaviour
{
    private Transform startPosition;
    private Transform spawnPosition;
    private Pin currentPin;
    private bool isGameOver = false;
    private int score = 0;

    public TextMeshProUGUI scoreText;
    public GameObject pinPrefab;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        spawnPosition = GameObject.Find("SpawnPosition").transform;
        SpawnPin();
    }

    // Update is called once per frame
    void Update()
    {
        if (isGameOver) return;
        if (Input.GetMouseButtonDown(0))
        {
            score++;
            scoreText.text = score.ToString();
            currentPin.StartFly();
            SpawnPin();
        }
    }

    void SpawnPin()
    {
        currentPin = GameObject.Instantiate(pinPrefab, spawnPosition.position, pinPrefab.transform.rotation).GetComponent<Pin>();
    }

    public void GameOver()
    {
        if (isGameOver) return;

        GameObject.Find("Circle").GetComponent<RotateSelf>().enabled = false;
        
        isGameOver = true;
    }
}
游戏结束动画

当游戏结束后,将主摄像头背景变为红色,并且使摄像头size变小,使得游戏内容放大

通过camera组件进行控制

GameManager

c# 复制代码
using UnityEditor.Tilemaps;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using TMPro;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using System.Collections;

public class GameManager : MonoBehaviour
{
    private Transform startPosition;
    private Transform spawnPosition;
    private Pin currentPin;
    private bool isGameOver = false;
    private int score = 0;
    private Camera mainCamera;

    public TextMeshProUGUI scoreText;
    public GameObject pinPrefab;
    public float speed = 3;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        startPosition = GameObject.Find("StartPosition").transform;
        spawnPosition = GameObject.Find("SpawnPosition").transform;
        mainCamera = Camera.main;
        SpawnPin();
    }

    // Update is called once per frame
    void Update()
    {
        if (isGameOver) return;
        if (Input.GetMouseButtonDown(0))
        {
            score++;
            scoreText.text = score.ToString();
            currentPin.StartFly();
            SpawnPin();
        }
    }

    void SpawnPin()
    {
        currentPin = GameObject.Instantiate(pinPrefab, spawnPosition.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);
    }
}
相关推荐
samble3 小时前
从零搭建灌装监控系统(十九):单元测试实战,xUnit + 内存SQLite + 反射测试私有方法
c#·wpf·mvvm·modbus·工业控制
人道领域6 小时前
【面试八股速通篇01】锁与并发工具
java·开发语言·面试·c#
宇卿.6 小时前
C#字段、属性、索引器、常量
开发语言·计算机视觉·c#
程序员Linc6 小时前
ONNXOCRSharp 开源手记 02|v0.4.0 PDF识别
开发语言·pdf·c#·ocr·onnxocrsharp
地狱为王7 小时前
Unity使用DPDFNet实现实时语音增强(降噪)
unity·语音增强·降噪·dpdfnet
慧都小妮子7 小时前
MSG 附件太占内存?Aspose.Email for .NET 26.9 延迟加载
c#·.net·aspose·内存优化·延迟加载·aspose.email·附件内存
慧都小妮子7 小时前
FastReport PDF/UA 导出:让出海 PDF 满足无障碍合规要求
pdf·c#·fastreport·报表导出·pdf/ua·pdf 无障碍
平行云PVT8 小时前
国产信创实时云渲染解决方案:如何实现数字孪生与三维应用云化部署?
unity·webrtc·unreal engine·实时云渲染·国产信创·摩尔线程·砺算科技
夏炎黄8 小时前
Terrain地形剪裁
unity
小贺儿开发10 小时前
DeepSeek + Codex + MCP:Unity 游戏开发实测
科技·游戏·unity·ai·程序员·编程·deepseek