arkanoid/Assets/Scripts/BlockBouncer.cs
2021-03-18 13:57:21 +01:00

76 lines
2.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockBouncer : MonoBehaviour
{
private Block parent;
void Start(){
parent = this.GetComponent<Block>();
}
void OnTriggerEnter(Collider other)
{
var ballMovement = other.GetComponent<BallMovement>();
if (ballMovement != null){
var contractPoint = this.GetComponent<Collider>().ClosestPointOnBounds(other.transform.position);
var vec = bounceVector(new Vector2(contractPoint.x,contractPoint.z));
Debug.DrawRay(contractPoint,new Vector3(vec.x,1,vec.y),Color.green,10);
ballMovement.BounceTo(vec);
this.parent.OnHit();
}
}
// Warning: Shitty code
private Vector2 bounceVector(Vector2 colPos)
{
var pos = new Vector2(this.transform.position.x,this.transform.position.z);
var hWidth = this.GetComponent<Collider>().bounds.size.x / 2f;
var hHight = this.GetComponent<Collider>().bounds.size.z / 2f;
var topRight = pos + new Vector2(-hWidth,-hHight);
var topLeft = pos + new Vector2(hWidth,-hHight);
var botRight = pos + new Vector2(-hWidth,hHight);
var botLeft = pos + new Vector2(hWidth,hHight);
if (colPos.y >= (pos.y - hHight)){
// 1 2 3
if (colPos.x >= (pos.x + hWidth)){
// 1
return Vector2.left;
}else if (colPos.x <= (pos.x - hHight)){
// 3
return Vector2.right;
}else{
// 2
return Vector2.down;
}
}else if (colPos.y >= (pos.y + hHight)){
// 6 7 8
if (colPos.x >= (pos.x + hWidth)){
// 6
Debug.Log("6");
}else if (colPos.x <= (pos.x - hHight)){
// 8
Debug.Log("8");
}else{
// 7
return Vector2.up;
}
}else{
// 4 5
if (colPos.x >= pos.x){
// 4
Debug.Log("4");
}else{
// 5
Debug.Log("5");
}
}
return new Vector2(0f,0f);
}
}