- Home /
Having problems when trying to grab an object
Well, I've been trying to create a simples first game, and then try to build on top of it adding more machanics as I see myself interested, and the initial premise is to grab an object (a sphere) with the player character (a cube) and place it somewhere, if the sphere is placed correctly it would open a door and you would go to the next level, well, I made the walking controller, able to move and jump and etc, but i cannot make the player grab the sphere, and don't know why, can someone help? I'll copy and paste the scripts i have, what i do is basically to call an event every time "Fire02" is pressed (right mouse button) in the player walking controller, and then on the "hitboxActivation" script (wich is the script that is attached to a hitbox that moves with the player right in front of him) I run a method every time that event is called, and that method enables the hitbox (wich is also a trigger), but from here onwards i cannot do what i want, dont know why, i try to parent the sphere to the hitbox and then undo the parenting, but it wont happen.
Player Controller: (sorry for the messy script)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public enum FacingDirection { North, East, South, West, NorthEast, NorthWest, SouthEast, SouthWest }
public class PlayerController : MonoBehaviour { //References: public Rigidbody rb; public BoxCollider BCol; public Transform Player;
//Masks:
public LayerMask groundLayers;
public LayerMask mask;
//Settings for movement:
public float walkSpeed = 15f;
public float jumpSpeed = 50f;
public float interactionDuration = 100f;
//Vars that get player inputs
float Hmovement;
float Vmovement;
//Bools for checking:
bool movReq;
bool jumpReq;
bool grounded;
//public bool picked;
//Vector3 vars:
Vector3 walkVelocity;
Vector3 playerSize;
Vector3 boxSize;
Vector3 prevWalkVelocity;
public Vector3 boxOffset = new Vector3(-0.8f, 0f, -0.08f);
//Jump Velocity
[Range(1, 50)]
public float jumpVelocity;
[Range(1, 50)]
public float fallingVelocity;
//Grounded vars:
public float groundedSkin = 0.09f;
//Misc vars:
Quaternion Wt;
//Facings directions references:
FacingDirection facing;
//Delegates and Events:
public delegate void FacingChangeHandler (FacingDirection fd);
public static event FacingChangeHandler OnFacingChange;
public delegate void HitboxEventHandler(float dur);
public static event HitboxEventHandler OnInteract;
//public delegate void DropperHandler(Collider col);
//public static event DropperHandler DropObject;
void Start ()
{
rb = GetComponent<Rigidbody>();
BCol = GetComponent<BoxCollider>();
playerSize = GetComponent<BoxCollider>().size;
Player = GetComponent<Transform>();
boxSize = new Vector3(playerSize.x, groundedSkin, playerSize.z) + boxOffset;
//picked = false;
}
void Update ()
{
//imagine logic for walking here (too big to put together
//Activation of Hitbox for interaction
if (Input.GetButton("Fire2"))
{
if (OnInteract != null)
{
OnInteract(interactionDuration);
}
}
//else if (Input.GetButtonDown("Fire2") && picked == true)
//{
// if (DropObject != null)
// {
// OnInteract(interactionDuration);
// DropObject(new Collider());
// }
// picked = false;
//}
//more code for character facing and more code for moving
}
HitboxActivation:
using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(BoxCollider))] public class HitboxActivation : MonoBehaviour {
public Transform PlayerHitbox;
float offset = 1f;
BoxCollider col;
Vector3 boxSize;
Vector3 sizeHitbox;
//collider duration:
float duration;
//secondary
public bool picked;
public bool touching;
void Awake()
{
PlayerController.OnFacingChange += RefreshFacing;
PlayerController.OnInteract += StartCollisionCheck;
//PlayerController.DropObject += DropMethod;
col = GetComponent<BoxCollider>();
sizeHitbox = GetComponent<BoxCollider>().size;
//InteractiveSphere = GetComponent<Transform>();
PlayerHitbox = GetComponent<Transform>();
col.enabled = false;
picked = false;
}
void Update()
{
if (col.enabled)
{
duration -= Time.deltaTime;
if (duration <= 0)
{
col.enabled = false;
}
}
}
void StartCollisionCheck(float dur)
{
col.enabled = true;
duration = dur;
}
void RefreshFacing(FacingDirection fd)
{
#region old method
// switch (fd)
// {
// case FacingDirection.North:
// col.center = Vector3.forward * offset;
// break;
// case FacingDirection.East:
// col.center = Vector3.right * offset;
// break;
// case FacingDirection.West:
// col.center = Vector3.left * offset;
// break;
// default:
// col.center = Vector3.back * offset;
// break;
// }
#endregion
col.center = Vector3.forward * offset;
}
void OnTriggerEnter(Collider col)
{
Debug.Log(col.name);
touching = true;
}
void OnTriggerExit()
{
touching = false;
}
//private bool TriggerEnter()
//{
// Quaternion playerRotation = new Quaternion(PlayerHitbox.transform.rotation.x, PlayerHitbox.transform.rotation.y, PlayerHitbox.transform.rotation.z, PlayerHitbox.transform.rotation.w);
// boxSize = new Vector3(sizeHitbox.x, sizeHitbox.y, sizeHitbox.z);
// return Physics.CheckBox(col.center, boxSize, playerRotation);
//}
void Update(Collider col)
{
if (touching && picked == false)
{
col.GetComponent<InteractiveObject>().SetParenting(PlayerHitbox);
picked = true;
}
if (touching && picked)
{
col.GetComponent<InteractiveObject>().DropParenting();
picked = false;
}
}
//void DropMethod(Collider col)
//{
// if (GetComponent<PlayerController>().picked == true)
// {
// col.GetComponent<InteractiveObject>().DropParenting();
// }
//}
}
Object Script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class InteractiveObject : MonoBehaviour {
public Transform InteractiveSphere;
public Transform PlayerHitbox;
public BoxCollider col;
public SphereCollider Scol;
public Rigidbody Srb;
void Start ()
{
InteractiveSphere = GetComponent<Transform>();
PlayerHitbox = GetComponent<Transform>();
col = GetComponent<BoxCollider>();
Srb = GetComponent<Rigidbody>();
gameObject.layer = 10;
}
public void SetParenting(Transform PlayerHitbox)
{
Srb.isKinematic = true;
transform.SetParent(PlayerHitbox);
}
public void DropParenting()
{
Srb.isKinematic = false;
transform.SetParent(null);
InteractiveSphere.transform.position = InteractiveSphere.transform.position;
}
}
Why are you overcomplicated the problem? What those enum directions good for? if your character is moving around then he must be rotating, just attach a collider in front of your character as children of character transform. Now you have a collider moving and rotating with him or her. When hit "fire2", get a list of colliding objects, if it is an object tagged with "object" then pick it up.
Those enums where an old thing, I dont use them now, i was following a tutorial series, but i deviated from it quite a bit. So how do i get a list of colliding objects ? And how do I pick it up?? I dont actually know how to do it
Answer by Obsessi0n · Jan 31, 2018 at 07:17 PM
You are complicating things way to much. This scripts will pick up items.
public LayerMask RayMask;
private RaycastHit hit;
private Transform currentTransform;
private float length;
void Update(){
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if(Physics.Raycast(TransformCamera.position, TransformCamera.forward, out hit, 3f, RayMask))
{
if(hit.transform.tag == "PickableObject")
{
SetNewTransform(hit.transform);
}
}
}
if (currentTransform)
MoveTransformAround();
}
public void SetNewTransform(Transform newTransform)
{
if (currentTransform)
return;
currentTransform = newTransform;
length = Vector3.Distance(TransformCamera.position, newTransform.position);
currentTransform.GetComponent<Rigidbody>().isKinematic = true;
//currentTransform.GetComponent<BoxCollider>().enabled = false;
}
private void MoveTransformAround()
{
if (currentTransform)
{
currentTransform.position = TransformCamera.position + TransformCamera.forward * 1.4f + TransformCamera.up * -0.6f;//length;
currentTransform.transform.rotation = TransformCamera.transform.rotation; // rotate
}
but my game isnt first person, it is 3rd person, so shooting a raycast out of the camera isnt what i need, I have a hitbox that set what the range for grabbing is, só i wanted to use that, and I am just interested in how i would be able to do grabbing and carrying objects with this system, Thanks for the help, im glad people are trying to help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612151631im_/https://answers.unity.com/themes/thub/images/avi.jpg)