【Unity】實現“擠開”效果(不使用自帶物理引擎)【改】
阿新 • • 發佈:2018-12-03
今天發現被撞擊的小球移動有些生硬,所以改了一下被撞擊之後小球的移動方式。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
//需要“擠開”的物體陣列
public GameObject[] targets;
//需要“擠開”的物體的邊界框
Bounds[] targetBound;
//自身的邊界框
Bounds bound;
//虛擬一個平面用來判斷目標位於自身的左邊或右邊
Plane plane;
//自身與目標物體的半徑和
Vector2[] dis;
//滑鼠點選的點
Vector2 clickPoint = Vector2.zero;
//是否移動
bool isMove;
//小球散開時移動速度
public float speed;
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)
{
Vector3 vector = targets[i].transform.position - this.transform.position;
Vector3 dir = vector.normalized;
targets[i].transform.Translate(dir * Time.deltaTime * speed);
}
}
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;
}
}
}
}
修改之後的撞擊效果,如圖:
到這就OK了!