I want my player to be able to press “E” to interact with an object. Every tutorial or answer I found is for FPS cameras and the range of pressing “E” is determined by the camera. However the game I’m working on has cameras in specific positions (like Resident Evil). Is there a way the player mesh can collide with a trigger range/area of an item and when it does, enable the player to interact with the object?
I think this is a pretty simple case of OnTriggerEnter. Make sure your character has a collider, and then create another collider around the object you want to interact with. Mark it as a trigger and make sure one of them has a rigidbody.
–
Beyond that I think it would be nice to also determine if the player is looking the in the same direction as the interactable. If they aren’t, and in the collider, probably shouldn’t be able to interact with it.
A simple solution would be to use the Dot product of the direction between the player and the interactable, to the players forward direction. Something like below for example:
–
Vector3 dir = (target.position - transform.position).normalized;
float delta = Vector3.Dot(dir, transform.forward);
// If delta is 1, it's looking directly at the object, -1 is looking directly away
// A good tolerance would be >= 0.8, then you can interact with the object
You could also check if the player is at a certain distance from the interactable object.
So
float distance = Vector3.Distance(objectA.transform.position, objectB.transform.position);
And then you check if the distance between them is enough so the player can interact
if(distance <= yourdistance)
{
if(Input.GetKeyDown(KeyCode.E))
// Player interacts with the object
}
This script would be attached to every the interactable object, not the player, and you could easily change the “yourdistance” value for every interactable making it a public variable.