How do I exclude an axis from 'transform.localPosition'?
I'm working on extending the Space Shooter Tutorial with some of my own custom elements. Within the GameOver state I'm trying to add a camera shake to my mainCamera. Below is all of the relevant code:
public float shake;
public float shakeStrength;
public Camera mainCamera;
private float shakeDecline;
void Update () {
if (shake > 0.0f) {
mainCamera.transform.localPosition = Random.insideUnitSphere * shakeStrength;
shake -= Time.deltaTime * shakeDecline;
} else {
shake = 0.0f;
}
}
public void GameOver () {
gameOverText.text = "GAME OVER";
shake = 1;
hudFrame.enabled = false;
hudFrameGameOver.enabled = true;
gameOver = true;
}
The transform code that I found works great except for one little problem.
The camera's position starts at (0, 10, 5). The position.y is far enough away to capture all of the game elements. When I run Random.insideUnitSphere, it affects all of the axis, which brings the camera's position on the Y axis close enough to chop off and hide other game objects from view.
Is there a way that I can still run Random.insideUnitSphere on X and Z, while leaving the Y value permanently at '10'?
Thank you!
Answer by NoseKills · Nov 04, 2016 at 03:48 PM
Do you mean the camera's parent object is at (0,10,5)? InsideUnitSphere returns vectors where all the values are in the range of -1 to 1, and you are setting that straight as the localPosition of the camera. If localPosition changes from (0,10,5) to for example (-0.6, -0.6, -0.6) that's a big change and might be the cause of your problems. But if the parent object is at (0,10,5) and you move the camera around the center of its parent (0,0,0) to (0.6, 0.6, 0.6), that could work.
You can "ignore" one axis from the random position like this
var randomOffset = Random.insideUnitSphere * shakeStrength;
randomOffset.y = 0;
mainCamera.transform.localPosition = randomOffset;
but another way to do this without parenting would be to store the position of the camera when the shake starts and then, when shaking, set the position to be the original position + random offset.