Minseok Kim
Minseok Kim

Reputation: 23

C++ Getting points between 2 points

So I have 2 points where I want to get points in between them for smoother teleport travel.

POINT a; //Character Position
POINT b; //Some random map position

I was using this formula to get a middle point first, but I want to add more points of travel before reaching POINT b.

POINT midpoint(const POINT& a, const POINT& b) 
    {
        POINT ret;
        ret.x = (a.x + b.x) / 2;
        ret.y = (a.y + b.y) / 2;
        return ret;
    }

I thought I could just calculate middle points more frequently to get shorter positions but I was wondering if there was a more dynamic way of doing this instead of coding in several different middle points.

I don't want to keep doing this simple approach:

POINT middlepoint = midpoint(a, b);
POINT closerpoint = midpoint(a, middlepoint);

How I want it to travel - number of points don't matter too much

Upvotes: 0

Views: 596

Answers (2)

David Grayson
David Grayson

Reputation: 87516

If your POINT class implements multiplication of a point by a float or double, and addition of two points (which are two handy operations to support), just make a float or double that changes from 0 to 1 over time, and do this:

float t = ...;  // changes from 0 to 1 over time
POINT intermediate = a * (1 - t) + b * t;

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54897

It's all just using proportions.

void MakePoints( const POINT& a, const POINT& b, int n, std::vector<POINT> & pts )
{
    pts.clear();
    pts.push_back( a );
    int dx = b.x - a.x;
    int dy = b.y - a.y;
    for( int i = 1; i <= n, i++ )
    {
        pts.emplace_back( a.x + dx * i / n, a.y + dy * i / n );
    }
}

Upvotes: 3

Related Questions