# 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;
Debug.Log(â€œtestâ€);
}
}

}

##### 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 on other sites

i dont quiet understand how to do it can you please explain a bit more

##### Share on other sites

This line is a problem:

if (passedt == intervale)

That's all I'll say, figuring out your own problems is integral to learning as a programmer.

##### 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 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 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.

Edited by Alberth

##### 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.

example:

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

## Create an account

Register a new account

• 10
• 18
• 13
• 10
• 12
• ### Similar Content

• Good day,

I just wanted to share our casual game that is available for android.

Description: Fight your way from the ravenous plant monster for survival through flips. The rules are simple, drag and release your phone screen. Improve your skills and show it to your friends with the games quirky ranks. Select an array of characters using the orb you acquire throughout the game.

Trailer:

• Hello fellow devs!
Once again I started working on an 2D adventure game and right now I'm doing the character-movement/animation. I'm not a big math guy and I was happy about my solution, but soon I realized that it's flawed.
My player has 5 walking-animations, mirrored for the left side: up, upright, right, downright, down. With the atan2 function I get the angle between player and destination. To get an index from 0 to 4, I divide PI by 5 and see how many times it goes into the player-destination angle.

In Pseudo-Code:
angle = atan2(destination.x - player.x, destination.y - player.y) //swapped y and x to get mirrored angle around the y axis
index = (int) (angle / (PI / 5));
PlayAnimation(index); //0 = up, 1 = up_right, 2 = right, 3 = down_right, 4 = down

Besides the fact that when angle is equal to PI it produces an index of 5, this works like a charm. Or at least I thought so at first. When I tested it, I realized that the up and down animation is playing more often than the others, which is pretty logical, since they have double the angle.

What I'm trying to achieve is something like this, but with equal angles, so that up and down has the same range as all other directions.

I can't get my head around it. Any suggestions? Is the whole approach doomed?

Thank you in advance for any input!

• By khawk
Watch the latest from Unity.

• By GytisDev
Hello,
without going into any details I am looking for any articles or blogs or advice about city building and RTS games in general. I tried to search for these on my own, but would like to see your input also. I want to make a very simple version of a game like Banished or Kingdoms and Castles,  where I would be able to place like two types of buildings, make farms and cut trees for resources while controlling a single worker. I have some problem understanding how these games works in the back-end: how various data can be stored about the map and objects, how grids works, implementing work system (like a little cube (human) walks to a tree and cuts it) and so on. I am also pretty confident in my programming capabilities for such a game. Sorry if I make any mistakes, English is not my native language.
• By Ovicior
Hey,
So I'm currently working on a rogue-like top-down game that features melee combat. Getting basic weapon stats like power, weight, and range is not a problem. I am, however, having a problem with coming up with a flexible and dynamic system to allow me to quickly create unique effects for the weapons. I want to essentially create a sort of API that is called when appropriate and gives whatever information is necessary (For example, I could opt to use methods called OnPlayerHit() or IfPlayerBleeding() to implement behavior for each weapon). The issue is, I've never actually made a system as flexible as this.
My current idea is to make a base abstract weapon class, and then have calls to all the methods when appropriate in there (OnPlayerHit() would be called whenever the player's health is subtracted from, for example). This would involve creating a sub-class for every weapon type and overriding each method to make sure the behavior works appropriately. This does not feel very efficient or clean at all. I was thinking of using interfaces to allow for the implementation of whatever "event" is needed (such as having an interface for OnPlayerAttack(), which would force the creation of a method that is called whenever the player attacks something).

Here's a couple unique weapon ideas I have:
Explosion sword: Create explosion in attack direction.
Cold sword: Chance to freeze enemies when they are hit.
Electric sword: On attack, electricity chains damage to nearby enemies.

I'm basically trying to create a sort of API that'll allow me to easily inherit from a base weapon class and add additional behaviors somehow. One thing to know is that I'm on Unity, and swapping the weapon object's weapon component whenever the weapon changes is not at all a good idea. I need some way to contain all this varying data in one Unity component that can contain a Weapon field to hold all this data. Any ideas?

I'm currently considering having a WeaponController class that can contain a Weapon class, which calls all the methods I use to create unique effects in the weapon (Such as OnPlayerAttack()) when appropriate.