Download the sample project here, let's use this project as the base for this tutorial.
We have an simple way to detect targeted peds, its the method Player.GetTargetedPed:
With this method and an gun (anything that will make you able to see the aim camera, for example an pistol or even an brick) you can detect the targeted ped, but its too much imprecise, for example if you aim at an car that has an driver, he will be detected as the target even if he is away from center of aim.
Also this method don't detects the peds that are Dead or in Ragdoll state.
My idea consists in get all possible targets, save then on an list, run this list and see who is closer to the center of the aim.
First lets create our list of possible targets, lets start with peds, this will be an global object so we can access it in the tick:
Now lets fill this list when the player press the aim button, so in the keydown event lets check for right mouse click and fill the list:
Now comes the main part, run the list in the tick and calc who is closer to center of aiming:
So, what is happening at each line?
- If Game.isGameKeyPressed(GameKey.Aim) AndAlso Exists(pedsToTarget) Then
here we check if the user is aiming and if the list is ready to be used
- Dim dist As Double
- Dim comparePosition As Vector3
- For Each p As Ped In pedsToTarget
- If Exists(p) AndAlso (p <> Player.Character) Then
- dist = p.Position.DistanceTo(Game.CurrentCamera.Position)
- comparePosition = Game.CurrentCamera.Position + Game.CurrentCamera.Direction * dist
- If p.Position.DistanceTo(comparePosition) < 0.5 Then
- p.ForceRagdoll(2000, True)
- p.ApplyForce(Vector3.WorldUp * 0.5, Vector3.WorldNorth)
- msg("detected", 10)
This is an exemplification of the calc:
The biggest problem with this technique is that we will get targeted peds that are behind walls and when the ped is fallen on ground the ped position is ~0.5 over what we expect as ped pos, this means that you need to aim a little up when he is fallen on ground.
The same idea can be used with vehicles, but to be more precise we will need to compare some extra positions not just the center of the vehicle:
we will need this additional variable in the tick:
we do the basic center position check:
and we compare to the "front position" too using GetOffsetPosition to obtain this position:
we multiply the Y (width) dimension of the model with 0.5 to obtain the half of the width and with relativeFront vector (one step forward)
we do the same with back, top, left and right position of the vehicle:
This makes more easy to target the vehicle when it is big like a bus or a truck, i personally prefer to check just the center position, in great part of cases is enough.
Download the Script of this tutorial.