Grabbing objects causes player object to tumble
Hello all. This is my first post, and I am just starting out.
I am working on an homage to Atari Adventure (learning purposes only), but I am running into a problem with replicating the 'grab by bumping into objects' mechanic. I have cobbled together a script that I am sure is very inefficient, but it works for the most part. The objects do attach, but once I detach them, my player object starts tumbling around like some momentum was stored or something. Any help would be greatly appreciated! :)
Here are the specs:
Player object (cube) Box Collider (w/material added to promote sliding rather than spinning) Rigidbody (all standard)
Item (cube) Box Collider (w/same material) + set to trigger
And here is my script:
using UnityEngine;
using System.Collections;
public class PlayerMove1 : MonoBehaviour {
public float speed;
private Rigidbody rb;
private bool hasObject = false;
private GameObject theChild;
private Vector3 offset;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
if (Input.GetKeyDown(KeyCode.Space)){
theChild.transform.parent = null;
hasObject = false;
theChild.GetComponent<Collider>().isTrigger = true;
}
}
void OnTriggerEnter(Collider hitThis)
{
if (hitThis.CompareTag("Item") && !hasObject){
//change scene
offset = hitThis.transform.position - transform.position;
hitThis.transform.position = transform.position + offset * 2;
hitThis.transform.parent = this.transform;
hitThis.isTrigger = false;
hasObject = true;
theChild = hitThis.gameObject;
}
}
}
Still not sure what made this happen. Has anyone else had this issue?