Hi all, i have a character (3rd person) and a gameobject (box). I want the char to push (only) the box and here i use AddForce with OnCollisionStay. The code is:
using UnityEngine;
using System.Collections;
public class PushBox : MonoBehaviour
{
private bool push;
public float thrust;
private Rigidbody m_Rigidbody;
private Animator m_Animator;
private bool m_Pushing;
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
m_Animator = GetComponent<Animator>();
}
public void Update()
{
m_Animator.SetBool("Push", m_Pushing);
}
void PushingBox()
{
push = Input.GetKey(KeyCode.Z);
if (push)
{
m_Rigidbody.AddForce(transform.forward * thrust);
m_Pushing = true;
}
if (!push) { m_Pushing = false; }
}
void OnCollisionStay (Collision other)
{
if (other.gameObject.tag == "Box")
{
PushingBox();
}
}
}
This work fine and I have adjust each of the mass gameobject so that the pushing work. But i got one anooying problem. When the char push the box in a position where the char and box not in line, like when pushing at the edge of the box (still collide), the box will change direction (rotate) and when the char keep pushing, until the char will not collide with the box. I assume it will stop the pushing because it’s not colliding anymore. But a strange behaviour occur. The char become freeze in moving (can not move forward, etc, only rotate) and the animation is still in push state animation (when ‘leaving the OnCollisionStay’). Is this a bug or I miss something here? I’m new in coding and still learning in Unity, though. Anyone know or maybe can help with this? Thanks in advanced.