How do I detect whenever a player looks at an entity?

So, I'm trying to make a gravity gun type thing in Minecraft. What I have so far is as follows.
A command block which is always powered and has the command:

/enchant @p sharpness 2

(it detects when you hold a sword).

And a command block which would be the output that has

execute @p ~ ~ ~ tp @e[type=villager] ^ ^ ^5 facing ^ ^ ^

Any help? I just need a command that detects if you look at a villager.


Solution 1:

Detection

/execute @p ^ ^ ^4 /testfor @e[type=villager,r=1]

You can increase the or decrease the number 4 to adjust the distance to the entity, and increase or decrease the 1 to adjust the size of the detection range.

How it works

It looks at 4 blocks ahead of the player’s look location and sees if there is a villager there.


By the way I’ve never seen that enchant command to detect a sword, really clever :)