Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by pedroka298 · Jan 31, 2018 at 12:43 AM · parentnewbieparentinggrabhitbox

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;
 }

}

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image NoDumbQuestion · Jan 31, 2018 at 02:17 AM 0
Share

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.

avatar image pedroka298 NoDumbQuestion · Jan 31, 2018 at 07:04 PM 0
Share

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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
         }





Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image pedroka298 · Jan 31, 2018 at 07:49 PM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

75 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Problem with Ammo Pickup 1 Answer

How to make multiple gameobjects child of one and the same transform (SCRIPT) 2 Answers

Animation precision? 0 Answers

Moving child transform also moves parent rigidbody 0 Answers

Set parent in the code (create GameObject hierarchy programatically) 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges