12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- //using DG.Tweening;
- public class Wallcollision : MonoBehaviour
- {
- BoxCollider boxCol = null;
- private void Start()
- {
- boxCol = GetComponent<BoxCollider>();
- }
- private void Update()
- {
- DetectionBox();
- }
- void DetectionBox()
- {
- //为盒子的左右两边伸出来1.4f个向量长度用于我们检测碰撞
- Vector3 scale = boxCol.transform.localScale + new Vector3(1.4f, 0, 0);
- //模拟的盒子中心点,x、y、z轴长度的一半
- Collider[] colliders = Physics.OverlapBox(boxCol.transform.position, scale / 2, boxCol.transform.rotation, LayerMask.GetMask("Detectcollisions"));
- print(colliders.Length);
- for (int i = 0; i < colliders.Length; i++)
- {
- print(colliders[i].name);
- //这只是一面墙体,其他方向类似,改轴向就是了
- //计算碰撞物体的z轴的一半宽度;
- float cube_z = colliders[i].GetComponent<MeshFilter>().sharedMesh.bounds.size.z;
- float scal_z = colliders[i].transform.lossyScale.z;
- float dqkd = cube_z * scal_z / 2;
- //计算墙体的x轴的一半宽度,
- float zqt_x = this.gameObject.GetComponent<MeshFilter>().sharedMesh.bounds.size.x;
- float zqtscal_x = this.transform.lossyScale.x;
- float qdkd = zqt_x * zqtscal_x / 2;
- //把这两个向量相加到时候我们物体作吸附运动就不会穿模,而是像吸附在墙上;
- float ydjl = dqkd + qdkd;
- //如果有DG.Tweening插件的朋友我建议用我注释的这行代码,毕竟有一个缓动效果;
- // colliders[i].transform.DOMove(new Vector3(colliders[i].transform.position.x, colliders[i].transform.position.y, this.transform.position.z - ydjl), 1);
- colliders[i].transform.localPosition = Vector3.MoveTowards(colliders[i].transform.localPosition, new Vector3(colliders[i].transform.position.x, colliders[i].transform.position.y, this.transform.position.z - ydjl), 2 * Time.deltaTime);
- }
- }
- }
|