- Home /
Empty/Game Object Gets Stuck inside after Colliding with another Object
Hey Unity 3D Community, I have a little newbie problem. I am creating a space invaders video game. The Current Project looks like this:
In the game there is a empty object that is moving along the X-axis, when the empty object hits the left wall the direction will change to 1 and it will move right, when it then hits the right wall, the direction will change to -1, and so forth. My problem is doing the same thing with the user, when I hit against a wall.
Here is the Code, for the moving empty object:
using UnityEngine;
using System.Collections;
public class enemyspawn_script : MonoBehaviour {
int direction = 1;
int speed = 1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
transform.Translate(new Vector3(direction * speed * Time.deltaTime, 0, 0));
}
void OnCollisionEnter(Collision col)
{
Debug.Log("hit");
if (col.gameObject.tag == "Left")
{
direction = (-1);
}
if (col.gameObject.tag == "Right")
{
direction = 1;
}
}
}
But when the empty game object collides, with a wall this happens:
The object gets stuck, in the wall a little bit. I need help to figure our how to make the object bounce off smoothly against a wall, or bumper, or object.
Answer by Owen-Reynolds · Jun 16, 2013 at 03:27 PM
The quickest way is to grow the wall colliders a little bit, or grow the enemy collider a little, or shrink the wall mesh a little. The exact same overlap will happen, but it will look better.
The "real" problem is that your code manually moves the object like an Inspector drag. That's fine, but it happily lets you drag through solid objects. Suppose you completely redid the movement to use rigidybody.velocity
(or AddForce, etc...) and let the system do the moving. Then the frame it was going to sink into the wall, the system would "know" it counts as a real moving object, so would bounce.
But there will almost always be a tiny bit of overlap.
Answer by KG3 · Jun 16, 2013 at 03:19 PM
It turns out that I am a idiot.
I tagged the Right Wall "left" and the Left Wall "Right", so when The game object hit The right wall it was reading in Left.