Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Object keeps spinning

Discussion in 'Scripting' started by DKGJames, Aug 29, 2018.

  1. DKGJames

    DKGJames

    Joined:
    Jan 3, 2018
    Posts:
    4
    When ever I run the game and the gameobject hits player 2 it keeps on spinning instead of going back to player 1. Please help.

    void FixedUpdate () {
    rb.AddForce(transform.up * (speed * Time.deltaTime));
    }
    void Hit()
    {
    if (hit == 2)
    {
    rand = Random.Range(1, 3);
    if (rand == 1)
    {
    transform.Rotate(0, 0, threetoone);
    spot = 1;
    }
    if (rand == 2)
    {
    transform.Rotate(0, 0, 180);
    spot = 2;
    }
    }
    }
    private void OnCollisionEnter2D(Collision2D coll)
    {
    if (coll.gameObject.name == "Player1")
    {
    Debug.Log("Hit1");
    hit = 1;
    Hit();
    }
    if (coll.gameObject.name == "Player2")
    {
    Debug.Log("Hit2");
    hit = 2;
    Hit();
    }
    }
     
  2. joshcantcode

    joshcantcode

    Joined:
    Aug 20, 2017
    Posts:
    6
    You're using rb.AddForce in FixedUpdate(), and calling transform.Rotate when a player collides.

    Use this as a base and fix it up from your end!


    Code (CSharp):
    1. void FixedUpdate () {
    2.     rb.AddForce(transform.up * (speed * Time.deltaTime));
    3. }
    4.  
    5. void Hit ( ) {
    6.     if (hit == 2) {
    7.         rand = Random.Range(1, 3);
    8.        
    9.         if (rand == 1)
    10.             rb.AddForce(transform.up * (new Vector3(0, 0, threetoone) * Time.deltaTime));
    11.             spot = 1;
    12.         } else if (rand == 2) {
    13.             rb.AddForce(transform.up * (new Vector3(0, 0, 180) * Time.deltaTime));
    14.             spot = 2;
    15.         }
    16.     }
    17. }
    18.  
    19. private void OnCollisionEnter2D (Collision2D coll) {
    20.     if (coll.gameObject.name == "Player1") {
    21.         Debug.Log("Hit1");
    22.         hit = 1;
    23.         Hit();
    24.     }
    25.     if (coll.gameObject.name == "Player2") {
    26.         Debug.Log("Hit2");
    27.         hit = 2;
    28.         Hit();
    29.     }
    30. }