Search Unity

How to properly aim at 3D point with offset ?

Discussion in 'Scripting' started by bart_the_13th, Sep 7, 2021.

  1. bart_the_13th

    bart_the_13th

    Joined:
    Jan 16, 2012
    Posts:
    498
    So, I'm revisiting my 3 years old aim code, and trying to do some fix(Just noticed that the code was actually a hack) I'm trying to aim at a point which is raycasted from a camera at forward direction, its kind of work, kind of, but the player wont aim properly if the distance from camera to the rayhit point is too close I wonder if my code is actually right...

    inside Update()
    Code (CSharp):
    1. ...
    2. //gun position offset from torso pivot point
    3. Vector3 gunOffset = -gun.transform.InverseTransformPoint(UpperTorso.position);
    4. aimTargetLerp        = Quaternion.LookRotation(rayHit.point - (UpperTorso.position + camTransform.rotation * gunOffset));
    5. torsoOffset = aimTargetLerp;
    6. ...
    7.  
    inside LateUpdate()
    Code (CSharp):
    1. v3 = Vector3.zero;
    2. v3.z = torsoOffset.z;
    3. v3.y = (recoilEffect - torsoOffset.x);//you can ignore recoilEffect
    4. v3.x = hitEffect + camTransform.eulerAngles.y - torsoOffset.y;
    5. UpperTorso.Rotate (v3, Space.Self);
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    358
    With space in front of you, the whole situation looks like this:
    Player - GunPosition - HitPoint

    But when the wall is close it's:
    Player - HitPoint - GunPosition

    As you can see the result look direction will be inverted.

    One fix I see is to ignore HitPoint and rotate body + weapon simply by current camera.forward/rotation.

    Another fix is to ignore GunPosition and use vector BodyPosition -> HitPoint, body position can't go be behind wall, so it should work more reliable.
     
  3. bart_the_13th

    bart_the_13th

    Joined:
    Jan 16, 2012
    Posts:
    498
    That's what I thought too, but even when the gun position is between the player and hitpoint, the impact point is slightly off when the player aims up/down, so I think the offset might not get calculated correctly, maybe I need to get the offset in the LateUpdate, after the torsoOffset rotation is applied.

    I cant ignore hitpoint since the impact point will be off, especially when the target is near. But your another fix suggestion might works, right now her hip is the pivot point, that's why I need the gunoffset, maybe if I try using her shoulder as pivot instead, I can eliminate the need of gunoffset...

    Thanks