Wallcollision.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. //using DG.Tweening;
  5. public class Wallcollision : MonoBehaviour
  6. {
  7. BoxCollider boxCol = null;
  8. private void Start()
  9. {
  10. boxCol = GetComponent<BoxCollider>();
  11. }
  12. private void Update()
  13. {
  14. DetectionBox();
  15. }
  16. void DetectionBox()
  17. {
  18. //为盒子的左右两边伸出来1.4f个向量长度用于我们检测碰撞
  19. Vector3 scale = boxCol.transform.localScale + new Vector3(1.4f, 0, 0);
  20. //模拟的盒子中心点,x、y、z轴长度的一半
  21. Collider[] colliders = Physics.OverlapBox(boxCol.transform.position, scale / 2, boxCol.transform.rotation, LayerMask.GetMask("Detectcollisions"));
  22. print(colliders.Length);
  23. for (int i = 0; i < colliders.Length; i++)
  24. {
  25. print(colliders[i].name);
  26. //这只是一面墙体,其他方向类似,改轴向就是了
  27. //计算碰撞物体的z轴的一半宽度;
  28. float cube_z = colliders[i].GetComponent<MeshFilter>().sharedMesh.bounds.size.z;
  29. float scal_z = colliders[i].transform.lossyScale.z;
  30. float dqkd = cube_z * scal_z / 2;
  31. //计算墙体的x轴的一半宽度,
  32. float zqt_x = this.gameObject.GetComponent<MeshFilter>().sharedMesh.bounds.size.x;
  33. float zqtscal_x = this.transform.lossyScale.x;
  34. float qdkd = zqt_x * zqtscal_x / 2;
  35. //把这两个向量相加到时候我们物体作吸附运动就不会穿模,而是像吸附在墙上;
  36. float ydjl = dqkd + qdkd;
  37. //如果有DG.Tweening插件的朋友我建议用我注释的这行代码,毕竟有一个缓动效果;
  38. // colliders[i].transform.DOMove(new Vector3(colliders[i].transform.position.x, colliders[i].transform.position.y, this.transform.position.z - ydjl), 1);
  39. 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);
  40. }
  41. }
  42. }