- Home /
Using Raycast to pickup weapon, but not it's not moving with player
I'm using Raycasting to pickup a weapon on button click. When I do the weapon is parented to the RightHand bone but when I move the weapon doesn't move with me. Not sure what I'm doing wrong.
using UnityEngine;
using System.Collections;
using NN.UMAScripts;
public class HoldWeapons : MonoBehaviour {
public GameObject weaponToHold;
public GameObject hand;
public GameObject body;
// Use this for initialization
void Start () {
hand = GameObject.Find("RightHand");
body = GameObject.Find("MyPlayer");
}
// Update is called once per frame
void Update () {
PickupWeapon();
}
void PickupWeapon()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 10, Color.red);
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit) == true&&hit.collider.tag=="Pickup.Weapon")
{
weaponToHold = hit.collider.gameObject;
weaponToHold.transform.parent = hand.transform;
weaponToHold.transform.localPosition = new Vector3(0, 0, 0);
weaponToHold.transform.rotation = new Quaternion();
Debug.Log(weaponToHold.name);
}
}
}
}
Answer by dmg0600 · Sep 21, 2014 at 07:40 PM
Next time please try to put some order in your code, it is really difficult to read if it is not well spaced.
You are not parenting it to the hand, is the only thing you are missing. Use transform.parent like this:
public GameObject weaponToHold;
public GameObject hand;
public GameObject body;
// Use this for initialization
void Start () {
hand = GameObject.Find("RightHand");
body = GameObject.Find("MyPlayer");
}
// Update is called once per frame
void Update () {
PickupWeapon();
}
void PickupWeapon()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit) == true && hit.collider.tag=="Pickup.Weapon")
{
weaponToHold = hit.collider.gameObject;
weaponToHold.transform.parent = hand.transform;
Debug.Log(weaponToHold.name);
}
}
}
I updated my code and fixed the formatting. It's still not working. The RightHand object is being assigned correctly to hand, and the weaponObject initially looks like it gets parented to the hand but as soon as i move the weapon doesn't mov.
Have you seen in the hierarchy that it is actually being parented to the hand?
Does the waepon script have some code to force its position?
Your answer
Follow this Question
Related Questions
Picking up rigidbody objects 2 Answers
Raycasting to pick up an item problem 1 Answer
[Problem] Cant activate 2D objects with touch? 1 Answer
Problems with raycast 1 Answer
Problem With Raycast Pickup Using Touch 0 Answers