Search Unity

Player change direction

Discussion in 'Scripting' started by Steikepanne, Feb 20, 2018.

  1. Steikepanne

    Steikepanne

    Joined:
    Jan 30, 2017
    Posts:
    34
    Hello.
    I want my Player to change direction when he hits a wall by 180 degrees, but im not sure how to do it. I also want him to change the facing direction 180 degrees at the same time. The movement is just fine, its just the changing of direction i need some help with :)

    Code (CSharp):
    1. public class MoveTest : MonoBehaviour {
    2.  
    3.     public float Speed = 0.3f;
    4.  
    5.     private void FixedUpdate()
    6.     {
    7.         transform.Translate(Speed * Time.deltaTime, 0, 0);
    8.     }
    9.  
    10.     void OnTriggerEnter(Collider col)
    11.     {
    12.         if (col.gameObject.CompareTag("xFlip"))
    13.         {
    14.             //Make the direction of travel rotate 180 Degrees.
    15.             //Make the facing direction rotate 180 Deg.
    16.             Debug.Log("Hit");
    17.         }
    18.     }
    19.  
    20. }
     
  2. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    Flip the speed to a negative value? i.e. Speed = -Speed.
     
  3. Steikepanne

    Steikepanne

    Joined:
    Jan 30, 2017
    Posts:
    34
    I have tried doing that exact solution multiple times before, and I never got that to work.
    Now I got it to work, looks like I had some trouble with the trigger.
     
    BlackPete likes this.
  4. Steikepanne

    Steikepanne

    Joined:
    Jan 30, 2017
    Posts:
    34
    Made some minor changes and now it works just as I want it to :)

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MoveTest : MonoBehaviour {
    4.  
    5.     public float Speed = 0.3f;
    6.  
    7.     private void FixedUpdate()
    8.     {
    9.         //moves the Player at a constant speed.
    10.         transform.Translate(-Speed * Time.deltaTime, 0, 0);
    11.     }
    12.  
    13.     void OnTriggerEnter(Collider other)
    14.     {
    15.         if (other.gameObject.tag == "xFlip")
    16.         {
    17.             // Makes the facing and movement change by 180.
    18.             transform.Rotate(0, 180, 0);
    19.         }
    20.     }
    21.  
    22. }