How to make an object move again after being stopped by collision in Unity?

Posted by Matthew Underwood on Game Development See other posts from Game Development or by Matthew Underwood
Published on 2014-08-22T18:51:55Z Indexed on 2014/08/22 22:35 UTC
Read the original article Hit count: 260

Filed under:
|
|
|
|

I have a player object which position is always centered on the main camera's viewport. This object has a Rigidbody 2D, a box and circle collider. The player moves around a level, the level has a polygon collider attached.

I move the camera until the object hits against the collider, which stops the movement of the camera by setting its speed to 0. The problem happens when I want to move the camera / player object away from the collider. As the speed is already at 0, it cannot move away from the collider.

The script attached to the player object, checks for collisions and applies the speed to 0 on the main camera's test script.

using UnityEngine;
using System.Collections;

public class move : MonoBehaviour {
public float speed;
public test testing;
// Use this for initialization
void Start () {
     speed = 10F;
    testing = Camera.main.GetComponent<test>();
}

// Update is called once per frame
void FixedUpdate () {
    Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane));
    transform.position = new Vector3(p.x, p.y, -1);

}

void OnCollisionEnter2D(Collision2D col) {


    testing.speed = 0;

}
void OnCollisionExit2D(Collision2D col) {


    testing.speed = 10F;

}

}

This is the script attached to the main camera; just a simple script that changes the camera's position.

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {
public float speed;
public float translationY;
public float translationX;
// Use this for initialization
void Start () {

    speed = 10F;
}

void FixedUpdate () {
     translationY = Input.GetAxis("Vertical") * speed * Time.deltaTime;
     translationX = Input.GetAxis("Horizontal") * speed * Time.deltaTime;

    transform.Translate(translationX, translationY, 0);
}

}

The player object isn't kinematic and is a fixed angle, the colliders aren't triggers and the polygon collider isn't a trigger either.

The player is the red square, the collider is the pink area.

enter image description here

-- EDIT --

From the latest change the collider set up for the player

enter image description here

So if the X speed was disabled. It wouldnt move into the side of the polygon colider which is good, but yet you couldnt move away from it. And moving down would move inside the colider.

© Game Development or respective owner

Related posts about c#

Related posts about 2d