When I Raycast Hit Object set to fixed hand position.
The title might be confusing so sorry about that but basically I have a raycast script to hit the objects the player can pickup but currently it just destroys the game object. I want the player to be able to press E send the raycast and when it hits game object set the gameobject to the bottom right hand side of screen like their holding it. I have tried using transform and whenever I look up and down the object would move with it when I want it to stay always in bottom right until they place it.
Any help would be much appreciated!
My pickup code currently which just destroys game object:
public class PickUp : MonoBehaviour
{
public int distance;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Grab();
}
}
void Grab()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
Debug.DrawRay(ray.origin, ray.direction * distance, Color.red, 100, false);
if (Physics.Raycast(ray, out hit, distance))
{
if (hit.transform.CompareTag("Item"))
{
Debug.Log("Item Hit");
GameObject ItemGrabbed = hit.transform.gameObject;
Destroy(hit.transform.gameObject);
}
}
}
}
Answer by KoenigX3 · Apr 05, 2021 at 10:33 AM
Have you tried making the object a child of your character transform and then setting it's localPosition?
// This should be a reference to your character transform.
// If this script is on your character, just use 'transform'
// If not, get the reference by using GameObject.Find or
// make this variable 'public', then assign it through the Inspector.
Transform character;
void Grab()
{
// All your previous code here
if(hit.transform.CompareTag("Item"))
{
hit.transform.SetParent(character);
// 'offset' should be a Vector3 that represents the offset from the character transform. When set properly, it offsets the object so it looks like the character is holding it.
hit.transform.localPosition = offset;
}
}
Yes that works better. Now problem is when i look up and down the item does not move with camera so if i look up I want the item to still be in screen. Like have it camera locked in bottom right no matter where the player is looking.
Oh, sorry, i thought that was an undesired outcome. In that case, you could make it a child of your camera, so when the camera rotates, the object will also change its position.
It works horizontal motion but when i move mouse up and down object follows it still. Thanks for all your help you have helped enough but if you by chance know a little fix I'm missing it would be appreciated!
Your answer
Follow this Question
Related Questions
Add GameObject Raycast hits to a variable 1 Answer
Multiple game objects same script 0 Answers
How would I project a Gameobject onto the surface of another? 0 Answers
How can I get an object reference from a Raycast? 1 Answer
How can i assign a GameObject to another but only have some of its components? 1 Answer