• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
selve

[C++] Delayed action of srand() - coordinates for object

23 posts in this topic

Hi,
I've created the small program where the ball is moving all the time on the screen to random coordinates made like that:

[source lang="cpp"]srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 && abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;[/source]
It's included in while(!gameover) function. That moves the ball:

[source lang="cpp"]void moveBall()
{
if(ballposition.x > ballX)
{
ballposition.x -= ballspeed;
}
if(ballposition.x < ballX)
{
ballposition.x += ballspeed;
}
if(ballposition.y > ballY)
{
ballposition.y -= ballspeed;
}
if(ballposition.y < ballY)
{
ballposition.y += ballspeed;
}
}[/source]

The only problem is that the ball is moving to the right coordinates X and Y, then sometimes stays for a moment and then another move and so on. When I try to delete the "srand(time(NULL));" it causes the ball to move really fast in each direction but no lag. How can I fix this?
0

Share this post


Link to post
Share on other sites
I don't see any calls to rand() in that code, so I am having a hard time following what it's doing. What exactly are `randx' and `randy'?
0

Share this post


Link to post
Share on other sites
How is randx and randy being set?

I'm not yet sure if this is your problem, I think you should post a bit more code, but [i]srand(time(NULL));[/i] should (in most simple programs) only be called once: when your game starts up. Not every frame of your game.

Could you post your entire main loop, cutting out the portions that don't involve randomness or the ball movement? I'd like to see the flow of your code, to mentally walk through it and see what's up.
2

Share this post


Link to post
Share on other sites
What is the intent of your program? Should it pick a random point, move to it, pick a new point, moves slowly to it, etc, etc? Or should the ball just meander around in a random fashion?
0

Share this post


Link to post
Share on other sites
Oh, sorry. Random numbers are defined here:
[source lang="cpp"]#define randx rand()*100%1175
#define randy rand()*100%585[/source]

The whole code:

[source lang="cpp"]#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"
#include "SDL/SDL_image.h"
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#define randx rand()*100%1175
#define randy rand()*100%585

using namespace std;

SDL_Surface * screen;
SDL_Surface * background;
SDL_Surface * ball;
SDL_Rect ballposition;
SDL_Event event;
int mouseX, mouseY;
int ballX = randx, ballY = randy;
int oldx, oldy;
int ballspeed = 1;
bool gameover = false;

void moveBall()
{
if(ballposition.x > ballX)
{
ballposition.x -= ballspeed;
}
if(ballposition.x < ballX)
{
ballposition.x += ballspeed;
}
if(ballposition.y > ballY)
{
ballposition.y -= ballspeed;
}
if(ballposition.y < ballY)
{
ballposition.y += ballspeed;
}
}

int main(int argc, char * args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096);
Mix_Chunk * click = Mix_LoadWAV("sounds/click.wav");
screen = SDL_SetVideoMode(1280, 720, 32, SDL_DOUBLEBUF | SDL_SWSURFACE);
background = IMG_Load("images/texture.jpg");
ball = IMG_Load("images/ball.png");
ballposition.x = 500;
ballposition.y = 400;
ballposition.h = 80;
ballposition.w = 80;
while(!gameover)
{
srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 && abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;

while(SDL_PollEvent(event))
{
if(event.type == SDL_QUIT)
{
SDL_Quit();
return 0;
}
if(event.type == SDL_MOUSEMOTION)
{
mouseX = event.motion.x;
mouseY = event.motion.y;
}
if(event.button.button == SDL_BUTTON_LEFT
&&
( mouseX >= ballposition.x &&
mouseX <= ballposition.x + ballposition.w ) &&
( mouseY >= ballposition.y &&
mouseY <= ballposition.y + ballposition.h ) )
{
ballspeed++;
Mix_PlayChannel(0, click, 0);
}
}
moveBall();
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(ball, NULL, screen, &&ballposition);
SDL_Flip(screen);
}
}
[/source]

The point of the game is just to click on the moving ball which causes increase of its speed. Edited by selve
0

Share this post


Link to post
Share on other sites
With the srand line in your program, ballX and ballY are being set to a single value for an entire second, then changes to another value. This is because the 'time' function precision is only one second, and you're using that to seed the random number generator.

With the srand removed (it should be removed, generally you only want to seed your RNG once), then your code is setting ballX and ballY to a new value every single frame, so the balls movement is more volatile.

What I guess you really want to do is change your code so that srand is called only during program initialisation, and add a condition so that you only set ballX and ballY to new values once the ball has reached the target.
2

Share this post


Link to post
Share on other sites
So how should it look like?
I've did this in ball moving function:
[source lang="cpp"]if(ballposition.x == ballX && ballposition.y == ballY)
{
targetreached = true;
}
[/source]
And this in while(!gameover):
[source lang="cpp"]if(targetreached)
{
srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 && abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;
targetreached = false;
}
[/source]

But it is still not working ;/ The ball is just moving to one position and then doesn't move any more. Edited by selve
0

Share this post


Link to post
Share on other sites
[quote name='selve' timestamp='1353521483' post='5002965']
So how should it look like?
I've did this in ball moving function:
[source lang="cpp"]if(ballposition.x == ballX &amp;&amp; ballposition.y == ballY)
{
targetreached = true;
}
[/source]
And this in while(!gameover):
[source lang="cpp"]if(targetreached)
{
srand(time(NULL));
do
{
ballX = randx;
ballY = randy;
}while(abs(oldx-ballX) > 300 &amp;&amp; abs(oldy-ballY) > 300);
oldx = ballX;
oldy = ballY;
targetreached = false;
}
[/source]

But it is still not working ;/ The ball is just moving to one position and then doesn't move any more.
[/quote]

I'm sure I saw a couple of clever minds in this thread commenting on the behaviour of srand() and rand()
and also, where srand() should be placed due to this behavior: on startup.
I'm also sure you'll be better off not using #defines when you can avoid it.
0

Share this post


Link to post
Share on other sites
[quote name='selve' timestamp='1353520509' post='5002959']
[CODE]while(!gameover)
{
srand(time(NULL));[/CODE]
[/quote]
[quote name='selve' timestamp='1353521483' post='5002965']
[CODE]if(targetreached)
{
srand(time(NULL));
[/CODE]
[/quote]

You are not supposed to srand so much. srand should only be used right at the beginning of the program, in the main function.

[CODE]int main(void)
{
srand(time(0));
/*main loop...*/
return 0;
};[/CODE]

Also, don't use those misleading macros, just use the expression explicitly.
[CODE]
#define SCREEN_WIDTH 1175
#define SCREEN_HEIGHT 585
...
ballX = (rand() * 100) % SCREEN_WIDTH;
ballY = (rand() * 100) % SCREEN_HEIGHT;
[/CODE] Edited by ultramailman
2

Share this post


Link to post
Share on other sites
As SuperVGA is saying, call srand() a single time at the beginning of your program and don't use macros. You could also benefit from better variable names. In particular ballX and ballY look like they would describe the ball's position, but they actually represent the target position for the ball.

Since you are using ballposition.x and ballposition.y somewhere in the code, you must already have a type to represent positions, so use it: Instead of ballX and ballY have a single variable ball_target.

Also, what's the point of having oldx and oldy? In the part of the code where they are used it looks like the position of the ball already contains that information, and I am guessing the code would become more readable if you use that instead.

Oh, the `while' condition in the loop selects a random point that is in the 300-pixel-wide cross centered around the current location of the ball. Is that what the intention was? Edited by Álvaro
1

Share this post


Link to post
Share on other sites
Thanks all, now it's working.
Instead of using:
[source lang="cpp"]if(ballposition.x == balltarget.x && ballposition.y == balltarget.y)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/source]

I used:
[source lang="cpp"]if(abs(ballposition.x-balltarget.x)< ballspeed && abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/source] Edited by selve
0

Share this post


Link to post
Share on other sites
In C++, the preprocessor should generally be reserved for including files, include guards and other forms of conditional compilation (such as platform specific implementations). You should not use it for constants, or functions. There are places where it is of use, such as a custom ASSERT() macro.

So ultramailman's code should look like:
[code]
const int SCREEN_WIDTH = 1175;
const int SCREEN_HEIGHT = 585;
...
ballX = (rand() * 100) % SCREEN_WIDTH;
ballY = (rand() * 100) % SCREEN_HEIGHT;
[/code]

You can use helper functions to remove redundancy and help simply the code:
[code]
const int SCREEN_WIDTH = 1175;
const int SCREEN_HEIGHT = 585;
const int RANDOM_GRANULARITY = 100;

int random(int max) {
return (std::rand() * RANDOM_GRANULARITY) % max;
}

// ...

ballX = random(SCREEN_WIDTH);
ballY = random(SCREEN_HEIGHT);
[/code]

[quote]
But it is still not working ;/ The ball is just moving to one position and then doesn't move any more.
[/quote]
Are you sure targetreached becomes true? If so, does the logic for changing the ball's target get called?

Your code allows the ball's speed to be faster than a single pixel, yet you require the ball to perfectly hit the target pixel in order to compute a new target. An alternative is to test if the distance between the ball's position and the target position is less than the ball's speed.

Can you post a full copy of your current code?
2

Share this post


Link to post
Share on other sites
Here's the whole code:

[source lang="cpp"]#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"
#include "SDL/SDL_image.h"
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#define SCREEN_WIDTH 1175
#define SCREEN_HEIGHT 585

using namespace std;

SDL_Surface * screen;
SDL_Surface * background;
SDL_Surface * ball;
SDL_Rect ballposition;
SDL_Rect balltarget;
SDL_Event event;
int mouseX, mouseY;
int oldx, oldy;
int ballspeed = 3;
bool gameover = false;
bool targetreached = false;

void moveBall()
{
if(ballposition.x > balltarget.x)
{
ballposition.x -= ballspeed;
}
if(ballposition.x < balltarget.x)
{
ballposition.x += ballspeed;
}
if(ballposition.y > balltarget.y)
{
ballposition.y -= ballspeed;
}
if(ballposition.y < balltarget.y)
{
ballposition.y += ballspeed;
}
if(abs(ballposition.x-balltarget.x)< ballspeed && abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}
}

int main(int argc, char * args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096);
Mix_Chunk * click = Mix_LoadWAV("sounds/click.wav");
screen = SDL_SetVideoMode(1280, 720, 32, SDL_DOUBLEBUF | SDL_SWSURFACE);
background = IMG_Load("images/texture.jpg");
ball = IMG_Load("images/ball.png");
ballposition.x = 500;
ballposition.y = 400;
ballposition.h = 80;
ballposition.w = 80;
srand(time(0));
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
while(!gameover)
{
while(SDL_PollEvent(&amp;event))
{
if(event.type == SDL_QUIT)
{
SDL_Quit();
return 0;
}
if(event.type == SDL_MOUSEMOTION)
{
mouseX = event.motion.x;
mouseY = event.motion.y;
}
if(event.type == SDL_MOUSEBUTTONDOWN)
if(event.button.button == SDL_BUTTON_LEFT
&amp;&amp;
( mouseX >= ballposition.x &&
mouseX <= ballposition.x + ballposition.w ) &amp;&amp;
( mouseY >= ballposition.y &&
mouseY <= ballposition.y + ballposition.h ) )
{
ballspeed++;
Mix_PlayChannel(0, click, 0);
}
}
moveBall();
SDL_BlitSurface(background, NULL, screen, NULL);
SDL_BlitSurface(ball, NULL, screen, &amp;ballposition);
SDL_Flip(screen);
}
}
[/source] Edited by selve
0

Share this post


Link to post
Share on other sites
[quote][code] balltarget.x = (rand() * 100) % SCREEN_WIDTH;[/code][/quote]

That code basically picks a random column that is a multiple of the greatest common divisor of 100 and SCREEN_WIDTH. Are you sure that's what you want?
1

Share this post


Link to post
Share on other sites
[quote name='Álvaro' timestamp='1353525039' post='5002987']
[quote][code] balltarget.x = (rand() * 100) % SCREEN_WIDTH;[/code][/quote]

That code basically picks a random column that is a multiple of the greatest common divisor of 100 and SCREEN_WIDTH. Are you sure that's what you want?
[/quote]
So if I want a normal random not multiplied should I do this:

[source lang="cpp"]balltarget.x = ( (rand() * 100) % SCREEN_WIDTH) / 2;[/source] Edited by selve
0

Share this post


Link to post
Share on other sites
I've gone through your code in detail, if you are interested in feedback:
[code]
// I like to include the standard headers first
#include <iostream>
// Note: time.h is a C header. In C++, we use <ctime>
#include <ctime>
// This is also a C header, but it is unnecessary
// C++ has a built-in boolean type
// #include <stdbool.h>

// This is the recommended way to include SDL. It is works we
#include "SDL.h"
#include "SDL_ttf.h"
#include "SDL_mixer.h"
#include "SDL_image.h"

// This isn't actually used, so I've removed it
// #include <windows.h>

// Do not use #define for constants
// The preprocessor doesn't understand C++
const int SCREEN_WIDTH = 1280;
const int SCREEN_HEIGHT = 720;

// The size of the ball is fixed, so we can use a constant
// Alternatively, we could use ballImage->w and ballImage->h
const int BALL_SIZE = 80;

using namespace std;

// Note: no globals!

// This is a type to represent a position on the screen
struct Point
{
int x;
int y;
};

// This helper function returns true if "point" is inside "rectangle"
bool pointInRectangle(Point point, SDL_Rect rect)
{
// Using early returns from a boolean function makes it easier to
// write this function. The alternative would be a massive boolean
// expression that is harder to parse and understand.
if(point.x < rect.x || point.x > (rect.x + rect.w))
{
return false;
}

if(point.y < rect.y || point.y > (rect.y + rect.h))
{
return false;
}

return true;
}

// Instead of having lots of variables called "ball", we can
// wrap them all in a single structure with short names.
struct Ball
{
Point position;
Point target;
int speed;
};

// This is a helper function. We would otherwise have to duplicate this
// logic twice, once where the target has been reached, another time
// when we are initialisating the ball.
Point pickRandomTarget()
{
// I've removed the * 100 as has been discussed in the thread
// Also note the way we can infer the size of the target area
// rather than have extra constants for this
int x = rand() % (SCREEN_WIDTH - BALL_SIZE);
int y = rand() % (SCREEN_HEIGHT - BALL_SIZE);
Point target = { x, y };
return target;
}

// Passing the ball by reference means that we can avoid making
// "ball" a global, yet we can still change the value in main()
void moveBall(Ball &ball)
{
// This makes it a little easier to write this function
// Instead of having to write ball.position.x > ball.target.x
Point &position = ball.position;
Point &target = ball.target;

// These conditions are related, but mutually exclusive
// I've moved the second condition to an "else" clause
if(position.x > target.x)
{
position.x -= ball.speed;
}
else if(position.x < target.x)
{
position.x += ball.speed;
}

// The whitespace above helps they eye notice the
// transition from X to Y in this next segment
if(position.y > target.y)
{
position.y -= ball.speed;
}
else if(position.y < target.y)
{
position.y += ball.speed;
}

// Separating these expressions into a variables helps make
// the condition that follows more reasonable.
int distanceX = abs(position.x - target.x);
int distanceY = abs(position.y - target.y);

if(distanceX < ball.speed && distanceY < ball.speed)
{
target = pickRandomTarget();
}
}

int main(int argc, char * args[])
{
// Putting this first thing makes it hard to accidentally call
// rand() before the seed has been changed
srand(time(0));

// You need to check for errors when you call functions that may return them
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
// It is also nice to have a way of finding out what went wrong...
// This is really good when you distribute your game and you have
// to debug the game on someone elses computer!
cerr << "Failed to initialise SDL: " << SDL_GetError() << endl;
return 1;
}
// This is a neat trick to allow us to return early from main() without
// having to remember to call all the cleanup functions
atexit(&SDL_Quit);

// SDL_Mixer is another library whose initialisation must be checked for errors
if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) < 0)
{
// A better approach would be to disable sound in this case, but play
// on. We could set "click" to NULL to indicate this.
//
// This is the "easy" way: bail out immediately!
cerr << "Failed to initialise SDL_Mixer: " << Mix_GetError() << endl;
return 1;
}
atexit(&Mix_CloseAudio);

// Here, we can re-use our SCREEN_(WIDTH|HEIGHT) constants!
SDL_Surface *screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_DOUBLEBUF | SDL_SWSURFACE);
if(!screen)
{
cerr << "Failed to set video mode: " << SDL_GetError() << endl;
return 1;
}

Mix_Chunk * click = Mix_LoadWAV("sounds/click.wav");
if(!click)
{
cerr << "Failed to load click sound: " << Mix_GetError() << endl;
return 1;
}

SDL_Surface *background = IMG_Load("images/texture.jpg");
if(!background)
{
cerr << "Failed to load background image: " << IMG_GetError() << endl;
// This is what atexit() helps us avoid, but we cannot use atexit() for this
Mix_FreeChunk(click);
return 1;
}

SDL_Surface *ballImage = IMG_Load("images/ball.png");
if(!ballImage)
{
cerr << "Failed to load ball image: " << IMG_GetError() << endl;
// As you can see, it is getting worse!
// There are other ways to handle this, but we can manage for the moment.
Mix_FreeChunk(click);
SDL_FreeSurface(background);
return 1;
}

// It would be better to use a constructor, but one step at a time!
Ball ball;

// It is nice not to have magic numbers. Starting the ball in the center is
// as good as anywhere, but it will work better if the size of the screen is changed
ball.position.x = SCREEN_WIDTH / 2;
ball.position.y = SCREEN_HEIGHT / 2;

ball.target = pickRandomTarget();

// It is nice to make conditions such that they are naturally true
bool running = true;
// "while running" is (marginally) easier to understand than "while not game over"
while(running)
{
// We can declare this event just before use, avoiding the need for a global
SDL_Event event;
while(SDL_PollEvent(&event))
{
// Again, these conditions are related but mutually exclusive
// So I've chained them.
if(event.type == SDL_QUIT)
{
// By ending the loop here, we naturally fall off the end of main()
// This runs our cleanup code
running = false;
}
else if(event.type == SDL_MOUSEBUTTONDOWN)
{
// I prefer to always include curly braces around every condition
// This makes it easier to change the program.
//
// Consider the following code:
// if(condition)
// actionA();
//
// Imagine we need to add a second action:
// if(condition)
// actionA();
// actionB();
//
// If the curly braces are forgotten, then actionA() remains conditional
// but actionB will be called unconditionally!
if(event.button.button == SDL_BUTTON_LEFT)
{
// There is no reason to track the position of the mouse
// The SDL Button event also tells us where the click occurred
Point mousePosition = { event.button.x, event.button.y };

// This is an example of bundling data needed by a function
// into one object, rather than resorting to globals
// or having lots of function parameters!
SDL_Rect ballRectangle = {
ball.position.x,
ball.position.y,
BALL_SIZE,
BALL_SIZE
};

// This is where our helper function comes in handy
// It really simplifies understanding this code
if(pointInRectangle(mousePosition, ballRectangle))
{
ball.speed++;
Mix_PlayChannel(0, click, 0);
}
}
}
}

// Remember, moveBall() takes a reference, so the values inside "ball"
// are actually updated
moveBall(ball);

SDL_BlitSurface(background, NULL, screen, NULL);
// Note: there is no need to fill in the width and height of this rectangle
// SDL takes the width and height of the blit from the "source" rectangle
// You've set that to NULL, so the entire image will be used.
SDL_Rect destination = { ball.position.x, ball.position.y };
SDL_BlitSurface(ballImage, NULL, screen, &destination);
SDL_Flip(screen);
}

Mix_FreeChunk(click);
SDL_FreeSurface(background);
SDL_FreeSurface(ballImage);

// Usually in C++, this isn't necessary
// main() has a special exception from the need to always explicitly return a value
// However, SDL #defines main to SDL_main, so it can provide platform specific
// code where necessary.
//
// This is a good example of the preprocessor conflicting with your code
return 0;
}
[/code]
This code isn't compiled or tested, so watch out!
2

Share this post


Link to post
Share on other sites
[quote name='selve' timestamp='1353524734' post='5002982']
I used:
[code]if(abs(ballposition.x-balltarget.x)< ballspeed && abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/code]
[/quote]
Wrong again. It should be:
[code] if(abs(ballposition.x-balltarget.x)< ballspeed || abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/code]
And no I am not talking about the difference in whitespace nor your use of [[b][/b]source] instead of [[b][/b]code].


L. Spiro Edited by L. Spiro
0

Share this post


Link to post
Share on other sites
But if would do " || " it will for example work like this:
The ball has reached Y point, but didn't reached X point, so the new X and the new Y are created.
And I want to do it if the ball reaches X and Y. Am I right?
0

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1353538444' post='5003054']
Wrong again. It should be:
[code] if(abs(ballposition.x-balltarget.x)< ballspeed || abs(ballposition.y-balltarget.y)< ballspeed)
{
balltarget.x = (rand() * 100) % SCREEN_WIDTH;
balltarget.y = (rand() * 100) % SCREEN_HEIGHT;
}[/code]
[/quote]
umm....no? (seriously, i'm trying to figure out why you think this would work, am i missing something?)
0

Share this post


Link to post
Share on other sites
I guess if you really intend to use "manhattan units" how about using
[code]
if( ( abs(ballposition.x-balltarget.x) + abs(ballposition.y-balltarget.y) ) < (ballspeed * 2) )
{
balltarget.x = rand() % SCREEN_WIDTH;
balltarget.y = rand() % SCREEN_HEIGHT;
}
[/code]

But as it seems to be about a ball, I feel inclined to suggest that you just use an actual velocity vector,
the root of the squares of dX and dY added. (Or don't do the root but work in squared units, if you can/want to.)

Even better, you could use a 2d vector struct
[code]
struct 2dmotionvector
{
float dx;
float dy;
float len;
float angle;
}
[/code]
To define your velocity, and work with that instead of having only independent x and y speeds to deal with.
-You can use len and angle primarily, and then set dx and dy if you need it in later statements.
(What if you apply spin to the ball, or it bounces off a surface? Way easier with 2d vector math on composite types in my opinion) Edited by SuperVGA
0

Share this post


Link to post
Share on other sites
Well, L.Spiro has a version that will at least trigger at all (when one coordinate is getting close enough), while the other version looks like in the end the ball will reach one coordinate first, then start jittering around on one axis, move only along the other axis and finally find a new destination. It also means that if one coordinate is reached, the balls will effectively move at only half the speed.

So obviously I second the approach of using vectors, simply because the other code only allows for 45° steps in motion and I doubt that sudden changes of direction while heading towards a destination are intended.
-1

Share this post


Link to post
Share on other sites
[quote name='slicer4ever' timestamp='1353598850' post='5003251']
umm....no? (seriously, i'm trying to figure out why you think this would work, am i missing something?)
[/quote]
My version is based on the logic in his first post. “If both coordinates move by over 300 units, generate new coordinates, but if only the X or the Y moves by over 300, that is fine.”

For his revision I only didn’t notice that he had switched from > to <, which achieves the correct results.

Comments would go a long way here. Don’t be afraid; they don’t bite. I really couldn’t look too terribly closely because there is not a single comment anywhere, although the code I “corrected” was small enough that I could have paid more attention there.


I still don’t really understand the goal behind the code, and again I would insist on using vectors. Makes everything simple.


L. Spiro
1

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  
Followers 0