I can’t understand why this isn’t working, I’m casting a ray to my mouse with a fairly simple script, but it seems to be casting it a little off to the left or right. If I try to cast straight up, it will cast maybe 10 degrees to the right? I’m casting the ray from the player, here’s my script,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class GrapplingHook : MonoBehaviour
{
public bool grappling;
LineRenderer ropeRenderer;
[SerializeField] Transform anchor,grappleHook;
Camera cam;
[SerializeField] float maxGrappleDistance = 20;
[SerializeField] LayerMask groundLayer;
private void Start()
{
cam = Camera.main;
ropeRenderer = GetComponent<LineRenderer>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
LaunchGrapple();
}
if (Input.GetMouseButtonDown(1))
{
ReleaseGrapple();
}
if (grappling)
{
ropeRenderer.positionCount = 2;
ropeRenderer.SetPosition(0, anchor.position);
ropeRenderer.SetPosition(1, grappleHook.position);
}
}
void LaunchGrapple()
{
RaycastHit2D hit = Physics2D.Raycast(anchor.position,cam.ScreenToWorldPoint(Input.mousePosition),maxGrappleDistance,groundLayer);
if (hit.collider != null)
{
grappling = true;
grappleHook.transform.position = hit.point;
}
}
void ReleaseGrapple()
{
grappling = false;
ropeRenderer.positionCount = 0;
grappleHook.transform.position = transform.position;
}
}
And here’s a video showing the issue,
So as you can see I’m drawing a line from the anchor position(which is a child of the player) to the grapple point(which is a child of the anchor) and moving the grapple point to the ray’s point. But why does it seem to be off? Unless I aim it at a perfect up-right or up-left angle…
Thanks.