hi,
i spent the whole day learning about RayCast, but how do I pick up an item, like picking up a flashlight while it’s still on? I’m only trying to get it to touch a Block and the devlog will notify me, but I can’t actually pick it up. Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
interface IInteractable
{
void Interact();
}
public class Interactor : MonoBehaviour
{
public Transform InteractorSource;
public float InteractionRange;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Ray r = new Ray(InteractorSource.position, InteractorSource.forward);
if (Physics.Raycast(r, out RaycastHit hit, InteractionRange))
{
if (hit.collider.TryGetComponent(out IInteractable interactable))
{
interactable.Interact();
}
}
}
}
}
}
using UnityEngine;
public class NumberGenerator : MonoBehaviour, IInteractable
{
public void Interact()
{
Debug.Log(Random.Range(0, 100));
}
}
All the tutorials and lessons I’ve found use Rigibody, but that conflicts with my playermoves because I’m using a character controller. Does anyone have any ideas? Please help me! My game is First-Person Perspective.
It is unclear what you are trying to achieve.
First I thought you want to take it and put it into your inventory.
That would be fairly simple: On Interact() you would add the respective item into your inventory (another class you would need) and destroy the game object you interacted with (Destroy(this.gameObject);)
But the note about the flashlight being on while picking it up made me wonder, if you would like to keep the flashlight in the world and just take it into the player character’s hand.
In that case you have (at least) two options:
Destroy the original game object and simply activate a Flashlight game-object that already is attached to your player (camera - or, if you can see your arms, a certain bone of the hand).
Do not destroy the original game object but instead attach it to the hand bone of your player characters right or left arm (transform.SetParent(...);) and zero out the local position (or assign an offset that makes it look good). If you want to make it look better, you could make a quick transition from it’s current world position / rotation, to the character’s hand world position / location before attaching it. A simple lerp is probably good enough if the transition is fast. However, this approach only works if the arms are really in front of the main camera and not rendered by another cam somewhere else. In the latter case you would need some trickery to make it look similar.