Is there any way to reduce this bit of Mathf.Clamp code for spawn positions down to one line?
I have a fairly basic stage set up where the players are spawned on the opposite side around natural zero of the world - they end up in positive / negative positions. I would like to clamp them so that neither can leave the 2D playing field. At current, I have that accomplished by using this snippet:
Vector3 SpawnClamp = _transform.position;
// Positive
if (PlayerIDNumber == 0)
{
SpawnClamp.x = Mathf.Clamp(SpawnClamp.x, SpawnPosition.x, -SpawnPosition.x);
}
// Negative
if (PlayerIDNumber == 1)
{
SpawnClamp.x = Mathf.Clamp(SpawnClamp.x, -SpawnPosition.x, SpawnPosition.x);
}
However, it feels like there must be a simpler way to do this without repeating the line twice. I would rather reduce it down to one or two lines of code - if it is at all possible. Can that be done?
If you make your playerID number 1 and -1 you can just multiply your positions with *PlayerID
and *-PlayerID
exactly my answer from 10 $$anonymous$$s ago but I need to be moderated before my answer is published, it seems :)
Answer by flashframe · Feb 23, 2016 at 03:26 PM
If you only have two player IDs you could use a ternary operator
Vector3 SpawnClamp = transform.position;
float _spawnPos = (PlayerIDNumber == 0)? SpawnPosition.x : -SpawnPosition.x;
SpawnClamp.x = Mathf.Clamp(SpawnClamp.x, _spawnPos, -_spawnPos);
flashframe's comment worked best! I only have two players - it's a simple combat game on a 1D/2D playing field. If it was an Answer, I could accept it!
@Teonnyn I made it an answer for you. Although you should also +1 mkdondor's answer, which is largely the same :-)
Your answer
Follow this Question
Related Questions
Please help me! Correct script) , 0 Answers
Raycast instantiation only sometimes working. 1 Answer
How can I make my turret also rotate on the X-axis? 0 Answers
Mathf.Clamp does not work at all. 1 Answer
Save object position after drag? 0 Answers