Sign in to follow this  

Unity Movement and speed issues

Recommended Posts

hello everyone !
i’m making a 2d game with unity  basically 4 objects are supposed to float in the play field with their speed increase over time i tried many scripts to get my movement as i wanted it to be but nothing seems to work i just want my objects to move and float in the play field and bounce when the collide with each other or with the walls also so speed increase is not working as time goes on the objects slow down and move very slowley and thats not what i want , i need my objects to keep moving and to gain speed as time goes on so i need help please here is my script



using UnityEngine;

public class Movement : MonoBehaviour
//speed of the ball
public float speed = 3f;
public float intervale = 5f;
public float accel = 2f;
public double passedt ;
//the initial direction of the ball
private Vector2 spawnDir;

//ball’s components
Rigidbody2D rig2D;
// Use this for initialization
void Start()
//setting balls Rigidbody 2D
rig2D = this.gameObject.GetComponent<Rigidbody2D>();

//generating random number based on possible initial directions
int rand = Random.Range(1, 4);

//setting initial direction
if (rand == 1)
spawnDir = new Vector2(1, 1);
else if (rand == 2)
spawnDir = new Vector2(1, -1);
else if (rand == 3)
spawnDir = new Vector2(-1, -1);
else if (rand == 4)
spawnDir = new Vector2(-1, 1);

//moving ball in initial direction and adding speed
rig2D.velocity = (spawnDir * speed);


private void FixedUpdate()
passedt = double.Parse(Timer.secondes);
if (passedt == intervale)
speed += accel * Time.deltaTime;
Vector2 veloc = new Vector2(speed, 0);
rig2D.velocity = veloc;
intervale += 5;



Share this post

Link to post
Share on other sites

You have an if statement that compares equality in floats. Don't do this. If you do need to check equality, you should use Mathf.Approximately.

In this case it looks like you're just checking if the timer has exceeded an interval. Check if the elapsed time is greater than the interval.

And instead of adding the base interval value to itself each interval, just reset the elapsed time.

if (timer > interval)
    timer = timer - interval;
    // whatever else happens each interval
Edited by cmac

Share this post

Link to post
Share on other sites

i think i didnt explain very well i checked equality because i want my speed to increase every 5 secondes that why i checked if the passed time is equal to interval and then i added 5 to the interval so it can keep track of the timer

Share this post

Link to post
Share on other sites

Yes, and that won't work. Think about why == on an timer float isn't working.

Even if you didn't know this was the issue, you can print debug logs in appropriate if statements that tell you what code is being executed, eg. Debug.Log("Timer interval passed, increasing speed") inside your if statement would never fire, which would indicate where the problem is.

Edited by cmac

Share this post

Link to post
Share on other sites
i dont quiet understand how to do it can you please explain a bit more

Basically, floating point numbers are approximations, they are always off from the "real" number by some small amount.

Thus if you test for one specific value, it is about 99% chance you'll get "false", even if the value is supposed to be the value you're testing for.


It's comparable with an assignment to throw a coin say 1 meter exactly. Even if we manage to agree on how we measure the distance, you will never succeed, as it's impossible to throw a coin 1,000000000000 meter (that's 1m accurate to 1nm).

With any float computation, the same happens, it's 1m, but not to 1nm accuracy. The cause is how computer systems store and perform floating point operations, so this problem happens with every computer system, in all computer languages.

The solution is to never test for a single value, as it will always return false. Instead, test for a range (Mathf.Approximately apparently, never used it), or test for a lower or upper bound, ie  value >= 1.0 works for all distances that are at least 1m.


For more information, search the interwebs for "what every programmer should know about floating point".

Edited by Alberth

Share this post

Link to post
Share on other sites

intervale is a float and passedt is a double. so its doing either a 32 or 64 bit cmp (comparison) of the two values. its HIGHLY unlikely that you just happen to call Parse(Timer.secondes) when the result is EXACTLY equal to interval. 


fixedUpdate runs and gets a passedt of 4.999999....

fixedUpdate runs the next time and gets a passedt of 5.00000000000001

right there you've missed the 5 second point.

it needs to be >=


one possible general algo for timers is:

1. start time = get_time()

2. repeat: ET = get_time() - start time. until ET>= desired ET.

ET is the same as your passedt and desired ET is the same as your intervale.

Edited by Norman Barrows

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By Afambus
      I have a full experienced team that looking for a composer and another 3d designer, im expecting as much from you there are other people in this server that can help you we have a determined team, we have done many things in our game there is more information in the discord about everyone and there skills there region and about the game, if you join the discord pm asap
    • By BAG Labs
      Mobile SoS

      Platform: Android
      Genre: Board
      Link: Google Play
      This games sharpen memory and test your strategies to place S-O-S pattern within time limit and serve 3 difficulties as Easy, Normal, and Hard.

      Goals of the game is to put S-O-S words in patterns (Horizontal, Vertical, and Diagonal) alternately with enemy.
      Single Player Multiplayer Achievements Leaderboards  



      Link: Google Play
      Please help us improve this game with review
    • By abarnes
      I am a game development student in my second year of a three year program and I would like to start building my portfolio. I was thinking of creating some games to show what I can do to potential employers since I wont have any work related experience when I graduate. But as I'm sure you all know there are tons of ways to approach developing/designing a game and I'm curious if anyone had any insight as to any "standards" that come with this? Is it okay to use game engines like Unity, Unreal, Game Maker etc? Or would it be better to make a game from scratch to better show case your skills? Any and all advice will be greatly appreciated!
    • By Hilster
      Hello 2D Artists,
      I've started making a 2D Puzzle Adventure game for mobile and I'm looking for someone who would want in on creating assets for the game. The core of the programming is pretty much complete, you can walk within the grid laid out and push boxes, when there is an object on top of a pressure pad it will activate the linked objects or if there is one object with multiple linked pressure pads it requires you to activate all points for the object to become active. 

      The level iteration for the game is quick and simple, a Photoshop file that is made of individual pixels that represents objects is put into the game and it creates the level out of those pixels with the assigned objects.
      The objects that need sprites created so far is the character, box, pressure pad, door, trap door, the walls, the stairs and the tiled background.
      I intend to add more objects so the amount I'd like to add will be extended.
      My motivations for posting here is to have something that looks nice to be able to display on my portfolio, so if you're looking for a working game that you can place your art into and improve the look of your portfolio then we're in business.
      Please reply with a few past examples of your art below and I'll be in touch!
    • By thefollower
      I have set up my TcpClient to connect to my server and that works fine. But i am a bit confused how i read messages from the network stream with it continuously running via async, without ever closing the connection ?
      My TcpClient Manager class has:
      public async Task<bool> Connect(string address, int port) { try { await _tcpClient.ConnectAsync(address, port); IsConnected = true; return true; } catch(Exception e) { Debug.Log(e); return false; } } public async Task<int> Read(byte[] readBuffer) { if (!IsConnected) return -1; using (var networkStream = _tcpClient.GetStream()) { try { var bytesRead = await networkStream.ReadAsync(readBuffer, 0, readBuffer.Length); return bytesRead; } catch (Exception e) { Debug.Log(e); IsConnected = false; return -1; } } }  
      So i thought to just run a co-routine and call Read constantly to get the most recent message, but that doesn't make much sense to me since a co-routine would be blocked with the await. How is this actually done? The MS Docs don't have very good Async examples with the TcpClient class so i don't know fully get how to keep calling Read correctly.
  • Popular Now