【问题标题】:Instantiate from raycast without intersect从不相交的光线投射实例化
【发布时间】:2021-07-30 19:33:11
【问题描述】:

所以我想知道如何在 Unity3D 中实例化一个没有交集的 GameObject。到目前为止,球体实例与我用射线投射击中的对象相交。我正在使用 hit.point 的位置,但想知道是否有办法在碰撞而不是对象的原点上生成它。这是我的参考代码:

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

public class BallSpawn : MonoBehaviour
{
    public int castLength = 100;
    public GameObject spawnObject;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //Input.GetMouseButton for infinite
        if (Input.GetMouseButton(0))
        {
            SpawnBall();
        }
            

    }

    public void SpawnBall()
    {
        RaycastHit hit;
        
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * castLength, Color.green, Mathf.Infinity);
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, castLength))
        {
            Instantiate(spawnObject, hit.point, hit.transform.rotation);
        }
    }
}

截至目前,球体会夹入地面并在生成时弹开。可以这么说,我希望球体被“放置”,以便它们在没有剪裁的情况下生成。

【问题讨论】:

    标签: c# unity3d instantiation


    【解决方案1】:

    您可以尝试将hit.point 替换为hit.point + hit.normal * ballRadius(当然您必须知道或能够得到球的半径是多少)。但这会导致某些生成位置关闭,尤其是当您以小角度撞击表面时。

    更好的选择是用Physics.SphereCast (transform.position, sphereRadius, transform.forward, out hit, castDistance) 替换光线投射。这应该会给你很好的结果,但你仍然必须像光线投射一样沿着命中法线添加球半径。

    【讨论】:

    • “想知道是否有办法在碰撞而不是对象的原点上生成它”。 hit.point 实际上是碰撞点。检查documentation
    • @rustyBucketBay 他可能是指碰撞/起源于生成对象的 POW。
    • 所以,生成对象的碰撞“盒子”。现在,我有球体,这是我生成的对象。每当我尝试生成它时,它都会穿过地板并弹跳出来。我想生成它,就好像我只是将球体放在地上一样,只是为了澄清。
    • 这些都不起作用。同样的结果仍然存在。
    • 我已经对其进行了测试,并且球在表面上产卵。这是我使用的确切代码:pastebin.com/6aM6qibs
    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多