I know this has been answered like 1000 times, but I just don't know how exactly should I code. All I want is when the platform changes its position on the x or the z axis, then rotate the whole platform by 90 degrees. I tried it with a platform.transform.Rotate(0, 90, 0), so I think there is more to do. The code itself:
public GameObject platform;
public Transform lastPlatform;
Vector3 lastPosition;
Vector3 newPos;
bool stop;
private Quaternion rotationQuaternion;
void Start()
{
lastPosition = lastPlatform.position;
StartCoroutine(SpawnPlatforms());
rotationQuaternion = transform.rotation;
}
void Update()
{
}
IEnumerator SpawnPlatforms()
{
while (!stop)
{
GeneratePosition();
Instantiate(platform, newPos, rotationQuaternion * Quaternion.identity);
lastPosition = newPos;
yield return new WaitForSeconds(0.1f);
}
}
void GeneratePosition()
{
newPos = lastPosition;
int rand = Random.Range(0, 2);
if (rand > 0)
{
newPos.x = 1.5f;
transform.rotation = rotationQuaternion * Quaternion.Euler(0, 90, 0); //one way i tried
}
else
{
newPos.z = 1.5f;
platform.transform.Rotate(0, 90, 0) //another way I tried
}
}
I appreciate all the help!
CodePudding user response:
So as I see it currently there are multiple issues / unclear things
- you are rotating about
90°
each0.1
seconds, so within 1 second you rotate about900°
. That sounds to me like it is simply way to fast. - You also rotate
transform
and not the platform platform
seems to be a Prefab in the assets so it makes no sense to rotate it
You probably want to do
void GeneratePosition()
{
newPos = lastPosition;
int rand = Random.Range(0, 2);
if (rand > 0)
{
newPos.x = 1.5f;
}
else
{
newPos.z = 1.5f;
}
// rather directly rotate the quaternion parameter
// if you are going to do the same thing in both cases anyway I would rather extract it right away
rotationQuaternion *= Quaternion.Euler(0, 90, 0);
}
and then also
// Rotating by "Quaternion.idendity" has no effect
Instantiate(platform, newPos, rotationQuaternion);
Still that sounds like a lot of spawning to me, maybe you would want to look into Object Pooling
CodePudding user response:
I managed to find a solution for the problem. Maybe could be helpful for someone, so here you go:
public struct SpawnPoint
{
public Vector3 position;
public Quaternion orientation;
public void Step(float distance)
{
if (Random.value < 0.5)
{
position.x = distance;
orientation = Quaternion.Euler(0, 90, 0);
}
else
{
position.z = distance;
orientation = Quaternion.Euler(0, 0, 0);
}
//orientation = Quaternion.Euler(0, 90, 0) * orientation;
}
}
void Start()
{
_spawn.position = lastPlatform.position;
_spawn.orientation = transform.rotation;
}
From now on, all what's left to do is Instantiate:
var newPlatform = Instantiate(platform, _spawn.position, _spawn.orientation);
Huge thanks to derHugo for giving me a start on how to do that!
CodePudding user response:
You can use this, it is from Unity3D documentation.
https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html