I'M reading the book "Beginning Game Development with Python and Pygame". The book showed me how to calculate the distance between two points using vectors. It first explained that you just subtract the values in the first point from the second. But just page or two pages later it says that in order to calculate the distance I need to get the square root of x squared + y squared. math.sqrt(self.x**2 + self.y**2)
The book seem to be describing the same thing in two completely different ways. Could someone please clarify this for me? Thanks.

Dani AI

Generated

They are describing two related steps, not two different distances. ’s book first shows how to form the difference between two points (subtract coordinates) — that gives the vector that points from one position to the other. and are describing the length of that difference vector (the Euclidean distance). In short: subtract to get the delta (dx, dy), then take the vector’s magnitude.

A compact, practical way to do this in Python without typing the sqrt formula directly is to use math.hypot, which handles the dx/dy combination and is numerically stable:

import math

dx = x2 - x1
dy = y2 - y1
distance = math.hypot(dx, dy)

If using Pygame, the Vector2 helper provides the same convenience and readable methods:

from pygame.math import Vector2

a = Vector2(x1, y1)
b = Vector2(x2, y2)
distance = a.distance_to(b)

Notes and tips: use the squared distance (dxdx + dydy) when you only need to compare distances to avoid the cost of a square root. Prefer math.hypot for better handling of very large/small values. For more details see the Python math.hypot documentation and the Pygame Vector2 reference.

Recommended Answers

All 2 Replies

Let's say we have a line from origin (0,0) to point (10,0) and another line to (0,10), intuitively they are equal length and actually when the lines are horizontal and vertical you can only substract the differing values: 10-0 = 10.

But you can also in this case to use the longer formula: ((10-0)**2-(0-0)**2)**0.5=(10**2)**0.5 = 10.

The distance between vectors, presuming you have vector A and B with two coordinates x and y, is:

sqrt(((Ax - Bx) ** 2) + ((Ay - By) ** 2))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.