- Home /
Change Direction[C#]
Hello i'm making an endless runner game and i want my character to turn multiple times.(change directions) i got it to work to change once and it doesn't want to change more please help this is my code,please help me:
private Vector3 direction = Vector3.right;
void Update()
{
controller1.Move(direction * Time.deltaTime * speed);
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Turn") ;
{
transform.rotation = Quaternion.Euler(0, 0, 0);
direction = Vector3.forward;
}
}
"doesn't want to change more " can you clarify? Unless the player is creating blocks that force turns (and triggering that event as a result), there's nothing here that "wants" to change anything?
Answer by JVene · Aug 23, 2018 at 06:55 PM
First, I hope this is merely a cut/paste mistake, but this wouldn't compile because there's a method declared inside a method. OnTriigerEnter should be outside the close bracket of the Update method.
That said, what you've posted only declares a fixed orientation. It always assigns the same orientation. What you require, it would seem to me, is a relative rotation. For that matter, it doesn't appear to me you're using 'direction' for anything. You've assigned the rotation to zero rotation in all axis on every occasion, which is to say this:
transform.rotation = Quaternion.Euler(0, 0, 0);
Is always a zero rotation, it never moves from that orientation.
I assume, without information, that you're rotating the object in the Y axis (you should adjust as you see fit). What you need is a value which indicates the rotation, which for Euler is safest in a range of -180 to 180 degrees. There are lots of ways you could do this, but try this:
Vector3 eulers = transform.rotation.eulerAngles;
transform.rotation = Quaternion.Euler(0, eulers.y + 90, 0);
I don't have any way of knowing that this is the exact form you require. If you rotate on the z axis, you would swap the last 0 of the call to Euler with the clause 'eulers.y + 90', but change that to 'eulers.z + 90' (note that this switches the axis to z instead of y). Further, maybe you're rotating the other way, in which case it wouldn't be '+ 90', it would be '- 90'.
Whatever the case aligns with your need, the point here is that this snippet takes the current orientation from the transform and adds to it (or subtracts from it) the relative rotation of 90 degrees. It should now turn every time this code 'fires'.
I don't know what you're doing with direction, but perhaps this impacts how you assign it, if it really has a purpose at this point. That is to say, it isn't always 'right' anymore.
Your answer
Follow this Question
Related Questions
[C#]CharacterController Turning 2 Answers
[C#] Movement Direction Change 2 Answers
Making a bubble level (not a game but work tool) 1 Answer
How to hold objects in third person? 1 Answer