- Home /
Grabbing a cube makes it expand and increase in size.
I have a cube in a game which I can grab and drop. The code below to do so works fine in that I can grab and drop the cube (with a key trigger or with a Touch controller). But every time I grab the cube, it's like it's being "stretched" and it increases in size to become a bigger cube, which I don't want to happen. I have executed this code before without this problem in a different project but now I can't figure out why the code to grab an object "stretches" its size and increases its volume. The cube is a rigid body with a box collider around it. Any help appreciated!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grab_supermrkt : MonoBehaviour
{
public OVRInput.Controller controller;
public string buttonName;
public float grabRadius;
public LayerMask grabMask;
private GameObject grabbedObject;
private bool grabbing;
void GrabObject()
{
grabbing = true;
RaycastHit[] hits;
hits = Physics.SphereCastAll(transform.position, grabRadius, transform.forward, 0f, grabMask);
if (hits.Length > 0)
{
int closestHit = 0;
for (int i = 0; i < hits.Length; i++)
{
if (hits[i].distance < hits[closestHit].distance) closestHit = i;
}
grabbedObject = hits[closestHit].transform.gameObject;
grabbedObject.GetComponent<Rigidbody>().isKinematic = true;
grabbedObject.transform.position = transform.position;
grabbedObject.transform.parent = transform;
}
}
void DropObject()
{
grabbing = false;
if (grabbedObject != null)
{
grabbedObject.transform.parent = null;
grabbedObject.GetComponent<Rigidbody>().isKinematic = false;
grabbedObject.GetComponent<Rigidbody>().velocity = 2 * (OVRInput.GetLocalControllerVelocity(controller));
grabbedObject.GetComponent<Rigidbody>().angularVelocity = OVRInput.GetLocalControllerAngularVelocity(controller);
grabbedObject = null;
}
}
// Update is called once per frame
void Update()
{
if (!grabbing && Input.GetAxis(buttonName) == 1)
{
GrabObject();
}
if (grabbing && Input.GetAxis(buttonName) < 1)
{
DropObject();
}
}
}
Answer by Bunny83 · Mar 21, 2018 at 12:20 AM
Just make sure the object where this script is attached to (as well as all parents of this object) has a scale of (1,1,1). Any non uniform scale can mess up an object attached as child.
Your answer
Follow this Question
Related Questions
Destroy Object on Mouse Click 5 Answers
Explosion before destroying 2 Answers
Something wrong with destroying script 0 Answers
How to display a picture with his own pixel size on a cube? 0 Answers