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*.distance < hits[closestHit].distance) closestHit = i;*
}
grabbedObject = hits[closestHit].transform.gameObject;
grabbedObject.GetComponent().isKinematic = true;
grabbedObject.transform.position = transform.position;
grabbedObject.transform.parent = transform;
}
}
void DropObject()
{
grabbing = false;
if (grabbedObject != null)
{
grabbedObject.transform.parent = null;
grabbedObject.GetComponent().isKinematic = false;
grabbedObject.GetComponent().velocity = 2 * (OVRInput.GetLocalControllerVelocity(controller));
grabbedObject.GetComponent().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();
}
}
}