- Home /
How to prevent mesh to not go through other meshes
I use a Raycast to render a mesh where ever I look. However, when it renders any mesh I use, it goes through the other objects.
Code:
RaycastHit Hit;
if (Physics.Raycast(direction.position, direction.forward, out Hit) && destinationPoint != null)
{
if (destinationPoint.transform.position != Hit.point)
destinationPoint.transform.position = Hit.point;
}
If I add Mesh Collider, it starts to move and rotate strangely and I'm also as a player moving too. How I can make this work? Doe anyone have a good proper solution to be able to render a mesh without going through other meshes but it can collides?
Ins$$anonymous$$d of instantiating at hit.point, add half the object bounds to the distance, normal to the wall.
Sounds tricky. I have a resource folder where I load objects to the game. So I'm not able to know always where is Pivot point of model. Can you provide a code or something to test it out?
But you have a renderer, and the renderer has bounds. Yes, it's "tricky", but if you have an arbitrary shape, you need to define some way of defining offset from wall, and that will vary for each object. Either do the maths, or add a special transform game object which you put on each object to define the "root" for wall mounting.
Statement thank you for your information but I have been learning unity for a month so I think I need some code to understand what you are saying. I have been learning from udemy courses and different videos to get the basics.
RaycastHit Hit;
if (Physics.Raycast(direction.position, direction.forward, out Hit) && destinationPoint != null)
{
Vector3 offset = GetItemOffset(item, Hit.normal);
Vector3 position = Hit.point + offset;
if (destinationPoint.transform.position != position)
destinationPoint.transform.position = position;
}
// ...
Vector3 GetOffsetForPrefab(GameObject item, Vector3 normal)
{
// Based on that normal, figure out what prefab requires
// so you can provide an offset. Up to you how you should solve it.
// Perhaps you want to base it off renderer bounds? Perhaps you want
// to solve it with an anchor point? Perhaps you want to solve it
// polymorphically with a component that figures it out for you?
// Perhaps you want to solve it based on colliders? Etc. Etc.
// var renderers = item.GetComponentsInChildren<Renderer>(); // ?
// var anchor = item.transform.Find("Anchor"); // ?
// var offsetCalculator = item.GetComponent<OffsetCalculator>(); // ?
// Do work based on method...
}
Answer by _Yash_ · Nov 05, 2015 at 01:35 PM
public float speed;
void Update(){
Vector3 target = hit.point; // where object should be
Vector3 source = trans.position; // where object is right NOW
// object should travel vel(distance) in speed(time) to reach the target
Vector3 vel = (hit.point - trans.position) * Time.deltaTime * speed;
rigidbodyOfObject.velocity = vel;
}
tweek the speed value to get the good result