Function problem

First of all this is not some homework! I am trying to make a trajectory of a ball, which are shot from the top of the screen with a velocity and falling in a gravitational field. My problem is that I'm trying to make a function thats return the x-coordinate and the y-coordinate. I have solved this by making two functions where I call both trajectory_x() and trajectory_y(). I would like to only call one function trajectory() and return two vectors x and y. Anyone know how I might do this? Or is it better to use another container?

Any help would really be appreciated :) And if you have questions please ask
Last edited on
You could try passing a pointer of a two element array to the function, then in the function store both vectors in the array. This would mean you wouldn't have to return anything, and get both values out of one function call. Personally I would just call two functions to get both values, but that is just me.
So, I'm guessing you want to write a function of time F(t) that returns both the i and j vector components of the ball (I'm reading vector as a math term, not an STL container).

You could use an STL pair to return two values. For example:
1
2
3
4
5
6
pair<int,int> f( int t )
{
    return make_pair( x_traj( t ), y_traj( t ) );
}

cout << f( time ).first << "," << f( time ).second << endl;


If you plan to extend this to 3D in the future, you could use a boost::tuple which can store the 3 values.
Last edited on
You could also use a strucure like this
1
2
3
4
5
6
7
8
9
10
struct position{
  double x;
  double y;
};

struct position ball;
ball.x = 1.;
ball.y = 1.;

position function(position);

So the function returns x and y in one stucture.
Thanks for the help :D

I solved my problem another way.. But my problem was I needed a method where I could get the x and y coordinates. But I had to make some boundaries conditions. My idea was to think of a screen with resolution 640x480 and then shot of the ball in the top center of the screen with a given angle. But when the ball hit one of the x edges it should bounce back, and terminate when hit bottom. But to make a long story short here was my final function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
vector<double> trajectory(double alpha_deg, int n) 
{
	int v0 = 20;
	double g = 0.8;
	double alpha_rad = alpha_deg*PI/180;
	vector<double> x (1,320);
	vector<double> y (1,0);
	double i = 0.01;
	while ( y.back() > -480 ) {
		x.push_back( 320 + v0*cos(alpha_rad)*i );
		y.push_back( (v0*sin(-alpha_rad)*i) - (0.5*g*i*i) );
		if (x.back() >= 640 ) {
			x.pop_back();
			x.push_back ( 960-v0*cos(alpha_rad)*i );
		}
		else if (x.back() < 0 ) {
			x.pop_back();
			x.push_back( -v0*cos(alpha_rad)*i - 320 );
		}
		i = i + 0.01;
	}
	if (n == 1)
		return x;
	else 
		return y;
}


I verified the functions validity with gnu plot. And if you have any questions please ask. And again thanks for your quick help :)
Topic archived. No new replies allowed.