Questions in regards to Isometric Angle Raycasting Via Mouse

I’m having trouble getting the direction of where I want my character to look and fire based on the mouse position. This is the standard looking in top down shooters where the character will rotate based on where the mouse is. I.e. if the mouse is to the left of the character they will rotate left.

  • I only need the direction rather than the point. Even if the mouse is close to the character it has to simulate a static distance of X away from the character.
  • With the code below, when the mouse is too close to the character it doesn’t follow the rule above.
  • Is it possible to clamp a point to have a min/set distance from another?

Below is the code which applies to the character’s bone rotation to look at the mouse. However I use a variation of it for the shooting as well.

    private void LateUpdate()
    {

        _lookTransform.LookAt(PointToLook());
        _lookTransform.rotation = _lookTransform.rotation * Quaternion.Euler((_offset));

    }

    private Vector3 PointToLook()
    {
        Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
        Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
        float rayLength = 0;
        if (groundPlane.Raycast(cameraRay, out rayLength))
        {
            Vector3 pointToLook = cameraRay.GetPoint(rayLength);
            return new Vector3(pointToLook.x, transform.position.y, pointToLook.z); //Look
        }
        return _lookTransform.eulerAngles; //Failed
    }

I don’t know what line 5 above is doing. Whatever it is doing is wiping out what line 4 is doing.

Line 4 should be all you need, assuming PointToLook() is correct. I would just delete line 5.

Test PointToLook() by creating a cube primitive and moving it there, get your mouse projection correct.

Probably just applying a rotation adjustment after performing the LookAt()

PointToLookAt() is expected to return a point, but you’re returning a angles.

return _lookTransform.eulerAngles; //Failed

I don’t know what the issue is you’re having. But if the mouse is right on the object center, the object will rotate (spin) fastly. You can prevent rotating the object if the mouse is too close to prevent unpredictable rotations.

        var pointToLook = PointToLook ();
        pointToLook.y = _lookTransform.position.y;

        //Only rotate object if mouse is a certain distance away from object
        if (Vector3.Distance (_lookTransform.position, pointToLook) > 1.0f) {
            _lookTransform.LookAt (pointToLook);
            _lookTransform.rotation = _lookTransform.rotation * Quaternion.Euler((_offset));
        }
        Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
        new Plane(Vector3.up,transform.position).Raycast(ray,out float p);
        transform.LookAt(ray.GetPoint(p));