Skip to main content
5 of 5
replaced http://stackoverflow.com/ with https://stackoverflow.com/

Add a flag to determine if the player has been stopped. At that point, stop setting the players position to the camera's, and instead some other input.

public float speed; public test testing; bool stopped = false; // Use this for initialization void Start () { speed = 10f; testing = Camera.main.GetComponent<test>(); } // Update is called once per frame void FixedUpdate () { if (!stopped) { Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane)); transform.position = new Vector3(p.x, p.y, -1); } else { //move away here } } void OnCollisionEnter2D(Collision2D col) { stopped = true; testing.speed = 0; } void OnCollisionExit2D(Collision2D col) { stopped = false; testing.speed = 10f; } 

###Edit

Seeing how you move the camera, in your camera script I would have two different speeds

public float speedX; public float speedY; public float translationY; public float translationX; // Use this for initialization void Start () { speedX = 10F; speedY = 10F; } void FixedUpdate () { translationY = Input.GetAxis("Vertical") * speedX * Time.deltaTime; translationX = Input.GetAxis("Horizontal") * speedY * Time.deltaTime; transform.Translate(translationX, translationY, 0); } 

Then you can omit the flag I talked about previously, and only modify speedY so the player can still move to the side.

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.speedY = 0; } void OnCollisionExit2D(Collision2D col) { testing.speedY = 10F; } 

###Edit 2

Using this SO question we can determine where the collision was. We can then modify our code to be

void OnCollisionEnter2D(Collision2D col) { var relativePosition = transform.InverseTransformPoint(col.contacts); if (abs(relativePosition.position.x) > abs(relativePosition.position.y)) testing.speedX = 0; else testing.speedY = 0; } void OnCollisionExit2D(Collision2D col) { testing.speedY = 10F; testing.speedX = 10F; } 
Liam McInroy
  • 391
  • 1
  • 4
  • 15