Hi
I am doing a 2d Raycast to hit objects to detect where the laser must stop. The laser go example 40 Long,
Once I hit and Object the laser length is just wrong and look to draw in reverse. Any help on this would be great.
When the ray hits the Coordinates looks correct in the debug log screen
Ray Not Hitting.
Ray Hitting and showing Hit Possition but LAser All wrong
using UnityEngine;
using System.Collections;
public class LaserScript : MonoBehaviour
{
[Header("Laser pieces")]
public GameObject laserStart;
public GameObject laserMiddle;
public GameObject laserEnd;
private GameObject start;
private GameObject middle;
private GameObject end;
void Update()
{
// Create the laser start from the prefab
if (start == null)
{
start = Instantiate(laserStart) as GameObject;
start.transform.parent = this.transform;
start.transform.localPosition = Vector2.zero;
//start.transform.rotation = transform.parent.rotation;
}
// Laser middle
if (middle == null)
{
middle = Instantiate(laserMiddle) as GameObject;
middle.transform.parent = this.transform;
middle.transform.localPosition = Vector2.zero;
//middle.transform.rotation = transform.parent.rotation;
}
// Define an "infinite" size, not too big but enough to go off screen
float maxLaserSize = 40f;
float currentLaserSize = maxLaserSize;
// Raycast at the right as our sprite has been design for that
Vector2 laserDirection = transform.right;
RaycastHit2D hit = Physics2D.Raycast(this.transform.localPosition, laserDirection, maxLaserSize);
Debug.DrawRay(this.transform.localPosition, hit.point, Color.yellow);
//Debug.DrawRay(this.transform.position, transform.right*maxLaserSize, Color.red);
if (hit.collider != null)
{
Debug.Log (hit.point);
// We touched something!
// -- Get the laser length
currentLaserSize = Vector2.Distance(hit.point, this.transform.position);
// -- Create the end sprite
if (end == null)
{
end = Instantiate(laserEnd) as GameObject;
end.transform.parent = this.transform;
end.transform.localPosition = Vector2.zero;
//end.transform.rotation = transform.parent.rotation;
}
}
else
{
// Nothing hit
// -- No more end
if (end != null) Destroy(end);
}
// Place things
// -- Gather some data
float startSpriteWidth = start.GetComponent<Renderer>().bounds.size.x;
float endSpriteWidth = 0f;
if (end != null) endSpriteWidth = end.GetComponent<Renderer>().bounds.size.x;
// -- the middle is after start and, as it has a center pivot, have a size of half the laser (minus start and end)
middle.transform.localScale = new Vector3(currentLaserSize - startSpriteWidth, middle.transform.localScale.y, middle.transform.localScale.z);
middle.transform.localPosition = new Vector2((currentLaserSize/2f), 0f);
// End?
if (end != null)
{
end.transform.localPosition = new Vector2(currentLaserSize, 0f);
}
}
}