Unity物体表面吸附

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、实现效果

请添加图片描述

二、代码

1.模拟VR

代码如下:

using UnityEngine;
using System.Collections;

public class SteamVRControllerBase : MonoBehaviour
{

    public static SteamVRControllerBase getInstance;
    private Transform sphere;          //点的位置,使用一个小球
    private Vector3 sphereNormal = Vector3.zero;      //点的法线方向
    public LayerMask _groundLayerMask;

    private void Awake()
    {
        getInstance = this;
        sphere = transform.Find("Sphere");
    }

    RaycastHit hitInfo;

    private void FixedUpdate()
    {
        Ray ray = new Ray(transform.position, transform.forward);
        if (Physics.Raycast(ray, out hitInfo, 1000f, _groundLayerMask))
        {
            sphere.position = hitInfo.point;         //复制位置
            sphereNormal = hitInfo.normal;           //获得法线方向
        }
    }
    //获取位置来控制画框的位置
    public Transform GetSphereTrans()
    {
        return sphere.transform;
    }
    //获取法线方向
    public Vector3 GetSphereNormal()
    {
        return sphereNormal;
    }
}

2.计算目标物体大小

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


public class AdsorbController : MonoBehaviour
{

    private Collider col;                 //通过碰撞体获得大小
    private Vector3 Velocity = Vector3.zero;
    private float smoothTime = 0.1f;

    private Vector3 length;                 //物体长宽高

    private void Start()
    {
        col = GetComponent<Collider>();
        length = col.bounds.size;
    }
    private void Update()
    {
        Vector3 targetPos = SteamVRControllerBase.getInstance.GetSphereTrans().position;
        //法线的起点需要向前移动半个物体宽度的距离,因为画框中心点在中间位置,否则会嵌入一半墙体
        Debug.Log(targetPos.x - (length.x * transform.lossyScale.x) / 2);
        targetPos = new Vector3(targetPos.x - (length.x * transform.lossyScale.x) / 2, targetPos.y - (length.y * transform.lossyScale.y) / 2, targetPos.z - (length.z * transform.lossyScale.z) / 2);
        //使用阻尼函数平滑移动效果
        transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref Velocity, smoothTime);
        Vector3 direction = SteamVRControllerBase.getInstance.GetSphereNormal();         //获取法线方向
        Debug.DrawRay(transform.position, direction);       //画出法线,用来测试
        transform.forward = direction;               //让画框前方与法线方向一致
    }
}

源码

链接:https://pan.baidu.com/s/1wHPHzcVTo0gPHQuGhaq6xg
提取码:5xj7

  • 18
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值