- Home /
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!!
Answer by robertbu · May 23, 2014 at 06:22 AM
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;
}
$$anonymous$$any many thanks! It worked perfectly! Thanks a lot! ^^
Your answer
![](https://koobas.hobune.stream/wayback/20220613145649im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Advice on my Ship AI... 4 Answers
Space Shooter Player 2 ship is flipping when going into Play Mode 0 Answers
How can i make the spaceship to land/take off with physics vertical ? 2 Answers