using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Positioner {
public static void FixPosition (GameObject GroundObject, Vector3 rayDir, RaycastHit hit, Vector3 firstPosition, bool normalRotated = false){
GameObject character = GameObject.Find("QualityManager");
// Normal based rotation for tagged objects
if (normalRotated == true){
GroundObject.transform.position = hit.point;
GroundObject.transform.LookAt (GroundObject.transform.position + hit.normal);
}
GroundObject.transform.position = firstPosition; //Move object to camera position - object keeps its scale and rotation
Vector3[] meshPoints = GroundObject.GetComponent<MeshFilter>().sharedMesh.vertices; //Get verts of object mesh
for ( int i = 0; i < meshPoints.Length; i++ ) {
meshPoints[i] = GroundObject.transform.TransformPoint( meshPoints[i] ); //Transform verts to world space (accounting for prefab rotation and scale)
}
/* List<Vector3> meshPoints = new List<Vector3>();
GroundObject.transform.position = Camera.main.transform.position; //Move object to camera position - object keeps its scale and rotation
//Get verts of object mesh
foreach (Transform current in GroundObject.transform) {
List<Vector3> meshPointsLocal = new List<Vector3>();
meshPointsLocal.AddRange(current.GetComponent<MeshFilter>().sharedMesh.vertices);
for ( int i = 0; i < meshPointsLocal.Count; i++ ) {
meshPointsLocal[i] = current.transform.TransformPoint( meshPointsLocal[i] ); //Transform verts to world space (accounting for prefab rotation and scale)
}
meshPoints.AddRange (meshPointsLocal);
}*/
GroundObject.SetActive( false ); //Turn object off so it doesnt interfere with raycast
float minDist = float.MaxValue;
for ( int i = 0; i < meshPoints.Length; i++ ) {
Ray pointRay = new Ray( meshPoints[i], rayDir ); //New ray from each vert, in the direction of the screen ray
//Debug.DrawRay( pointRay.origin, pointRay.direction * 5, Color.red, 4 );
RaycastHit rayHit;
if ( Physics.Raycast( pointRay, out rayHit ) ) {
if ( rayHit.distance < minDist ) {
minDist = rayHit.distance; //Find nearest ray hit
}
}
}
GroundObject.SetActive( true ); //Re-enable object
GroundObject.transform.position = GroundObject.transform.position + rayDir * minDist; //Move object to surface
}
}
It is a great code but there is one problem: If the ray start is close to a wall and the object is big enought the positioned mesh will go throught the wall. What could be the problem?