1. 程式人生 > >【Unity】實現“擠開”效果(不使用自帶物理引擎)

【Unity】實現“擠開”效果(不使用自帶物理引擎)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    //需要“擠開”的物體陣列
    public GameObject[] targets;
    //需要“擠開”的物體的邊界框
    Bounds[] targetBound;
    //自身的邊界框
    Bounds bound;

    //虛擬一個平面用來判斷目標位於自身的左邊或右邊
    Plane plane;
    //自身與目標物體的半徑和
Vector2[] dis; //滑鼠點選的點 Vector2 clickPoint = Vector2.zero; //是否移動 bool isMove; void Start() { //初始化 isMove = false; targetBound = new Bounds[targets.Length]; dis = new Vector2[targets.Length]; bound= this.GetComponent<Renderer>().bounds; for
(int i = 0; i < targets.Length; i++) { targetBound[i] = targets[i].GetComponent<Renderer>().bounds; dis[i] = bound.extents + targetBound[i].extents; } //print("邊界盒的中心" + bound.center); //print("邊界框的實際範圍。這個總是size的一半。" + bound.extents); //print("邊界盒的最大點,這個總是等於center + extents。" + bound.max);
//print("邊界盒的最小點,這個總是等於center-extents。" + bound.min); //print("邊界盒的總大小。這個總是extents的兩倍大。" + bound.size); } void Update() { for (int i = 0; i < targets.Length; i++) { if (Vector2.Distance(this.transform.position, targets[i].transform.position) < dis[i].x) { plane = new Plane(Vector3.left, this.transform.position); if (plane.GetSide(targets[i].transform.position)) { targets[i].transform.Translate(Vector2.left * Time.deltaTime * 2); } else { targets[i].transform.Translate(Vector2.right * Time.deltaTime * 2); } } } if (Input.GetMouseButtonDown(0)) { isMove = true; clickPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition); } CricleMove(); } /// <summary> /// 主角移動 /// </summary> void CricleMove() { if (isMove) { this.transform.position = Vector2.MoveTowards(this.transform.position, clickPoint, Time.deltaTime * 2); if (Vector2.Distance(this.transform.position, clickPoint) < 0.1f) { isMove = false; } } } }

目錄結構

新手不會發動圖所以沒法演示效果

剛入行的新手,望大佬多多斧正,謝謝!