- Home /
Raycast2D/Line Renderer offset on colliders based on mouse position
Hi all,
I've got a Raycast2D and Line Renderer question.
I have a character with a weapon that creates an aiming laser (Line Renderer) on right click. The X size is based on mouse position but will change when it hits a collider (Raycast2d) to where it registers a hit.
The script accounts for the origin being in the center of the player, thus when the origin is X = 0 the laser behaves as intended, however I need the origin to be from where the weapon is located on the player, X = 0.244 (for reference).
When changing the origin point the laser will will have an offset angle based on where it's hitting the collider and does not have an an angle coherent with mouse position.
How can I factor in the angle offset on collider hit with the mouse position? If that makes sense?
See code below:
using UnityEngine;
public class Laser : MonoBehaviour
{
public Camera cam;
public LineRenderer lineRenderer;
public Transform firePoint;
// Start is called before the first frame update
void Start()
{
DisableLaser();
}
// Update is called once per frame
void Update()
{
int layerMask = 1 << 9;
layerMask = ~layerMask;
if (Input.GetButtonDown("Fire2"))
{
EnableLaser();
}
if (Input.GetButton("Fire2"))
{
UpdateLaser();
}
if (Input.GetButtonUp("Fire2"))
{
DisableLaser();
}
}
void EnableLaser()
{
lineRenderer.enabled = true;
}
void UpdateLaser()
{
var mousePos = (Vector2)cam.ScreenToWorldPoint(Input.mousePosition);
lineRenderer.SetPosition(0, firePoint.position);
lineRenderer.SetPosition(1, mousePos);
Vector2 direction = mousePos - (Vector2)transform.position;
RaycastHit2D hit = Physics2D.Raycast((Vector2)transform.position, direction.normalized, direction.magnitude, layerMask: 9);
if (hit)
{
lineRenderer.SetPosition(2, hit.point);
lineRenderer.SetPosition(3, mousePos);
}
}
void DisableLaser()
{
lineRenderer.enabled = false;
}
}
Any help would be greatly appreciated! Many Thanks!
If i understand, you want to draw a line between the player and the resulting raycast object without snapping to its absolute coordinates.
@cweber4 yes, which I is what I was able to accomplish using the above, however the issue I was having was the offset and angle offset when I change the origin position. I was able to fix this though using the same origin position for both line renderer and raycast.
Vector2 direction = mousePos - (Vector2)firePoint.position;
RaycastHit2D hit = Physics2D.Raycast((Vector2)firePoint.position, direction.normalized, direction.magnitude, layer$$anonymous$$ask: 11);