Prevent 2D spaceship going out the screen

Hello, I have a problem from a time ago and I haven’t been able to find a correct answer for it, so here it is:

I’m implementing a 2D movement space game. I have 2 sprites, one for the background and another one for the spaceship and my camera’s bounds are inside the background.

I have the camera’s bounds and I can prevent the spaceship going through them, but when the spaceship stops, it doesn’t move again.

Here is a sample of my code:


	void FixedUpdate()
	{
		// Horizontal movement
		if(_xPosition >= _minXPosition && _xPosition <= _maxXPosition)
		{
			transform.Translate(Input.GetAxis("Horizontal") * _horizontalMoveSpeed * Time.deltaTime, 0, 0);
			_xPosition = transform.position.x;
		}

		// Vertical movement
		if(_yPosition >= _minYPosition && _yPosition <= _maxYPosition)
		{
			transform.Translate(0, Input.GetAxis("Vertical") * _verticalMoveSpeed * Time.deltaTime, 0);
			_yPosition = transform.position.y;
		}
	}

With this, I can move my spaceship and detect when it is going to go outside the camera, but when it stopts, it stays out.

Can u please help me with this?

Thank you a lot!!

The problems is that once you go out of bounds on your code, you code ignores all movement. A better solution would be to do the move and then clamp the result. Also there is no reason for this code to be executed in FixedUpdate(). Use Update():

void Update()
{	
	transform.Translate(Input.GetAxis("Horizontal") * _horizontalMoveSpeed * Time.deltaTime, 0, 0);
	transform.Translate(0, Input.GetAxis("Vertical") * _verticalMoveSpeed * Time.deltaTime, 0);

	Vector3 pos = transform.position;
	pos.x = Mathf.Clamp (pos.x, minXPosition, maxXPosition);
	pos.y = Mathf.Clamp (pos.y, minYPosition, maxYPosition);
	transform.position = pos;
}