Search Unity

Game Object Incorrect Asymmetric Movement

Discussion in 'Scripting' started by Mails_PR, Jan 3, 2019.

  1. Mails_PR

    Mails_PR

    Joined:
    Jul 30, 2018
    Posts:
    9
    Hello, everyone! I am currently working in the framework of the Space Shooter Tutorial and I am trying to make a boss-fight at the very end of the game. The boss is supposed to appear at the top of the screen, slowly go down to the upper-center and then start moving from right to left, and then left to right (the pattern is an endless loop). The script I am using is kind of working, but the boss does not make a full circle, but only around 80% of it, which bugs me a lot. It does move to the left, but does not move to the right to a full extent. Could someone tell me whether it is an issue with the following script? Thank you so much in advance!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BossMovementScript : MonoBehaviour {
    6.     public float speed = 20f;
    7.     public Rigidbody rb;
    8.        
    9.     void Start ()
    10.     {
    11.         rb = GetComponent<Rigidbody>();
    12.         Invoke("InitialBossMove", 3);
    13.         InvokeRepeating("BossMove", 6, 4);
    14.     }
    15.    
    16.     void InitialBossMove ()
    17.     {
    18.         rb.AddForce(transform.right * speed);
    19.         speed = speed * 2f;
    20.     }
    21.    
    22.     void BossMove ()
    23.     {
    24.         speed = speed * -1f;
    25.         rb.AddForce(transform.right * speed);
    26.     }
    27. }
    28.  
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Your InitialBossMove and BossMove methods aren't called every frame, so they don't apply a constant force to the boss' rigidbody. That can make it a little difficult to control, since you would then need to apply a very large force for a single frame; that can lead to inaccuracies. You might want to control the boss' movement in FixedUpdate instead.
    Code (csharp):
    1. private bool waitDone = false;
    2.  
    3. void Start()
    4. {
    5.     rb = GetComponent<Rigidbody>();
    6.     Invoke("InitialBossMove", 3);
    7.     InvokeRepeating("BossMove", 6, 4);
    8. }
    9.  
    10. void FixedUpdate()
    11. {
    12.     if(waitDone)
    13.         rb.AddForce(transform.right * speed);
    14. }
    15.  
    16. void InitialBossMove ()
    17. {
    18.     waitDone = true;
    19.     speed = speed * 2f;
    20. }
    21.    
    22. void BossMove ()
    23. {
    24.     speed = speed * -1f;
    25. }
    Note that you'll want a much smaller "speed" value.
     
  3. Mails_PR

    Mails_PR

    Joined:
    Jul 30, 2018
    Posts:
    9
    Thank you so much!
    Thanks a lot! It did make movement much smoother :) The problem was also alleviated when I played around a bit with the waiting/looping time.