I was going through a blog on Creating Lightning effect in 2D game.I wanted to implement the same in python. However I am stuck at a place.
Lets say startpoint and endPoint are co-ordinates in 2D plane , representing extreme points of a line segment.
Lets look at following Code Snippet from the blog:
midPoint = Average(startpoint, endPoint);
// Offset the midpoint by a random amount along the normal.
midPoint += Perpendicular(Normalize(endPoint-startPoint))*RandomFloat(-offsetAmount,offsetAmount);
.
Normalize(endPoint-startPoint):
That line gets a unit vector (vector of length 1) from startPoint to endPoint
Perpendicular(Normalize(endPoint-startPoint))
then gets a vector perpendicular to that (i.e. at right angles to the line)
I am not a regular python coder. Is there any in-built Normalise and Perpendicular Function in python that would help me in implementing the above code in python.
I don't know of built-in or third-party methods, but they are really simple:
This will print
You can call these functions with
or similar types.
Be aware that
normalize
will raise an Exception if the vector a has length zero.I decided to name my functions lower-case according to PEP 8, Python style guide.
As @SethMMorton and @ThoestenKranz indicated, numpy has a lot of support for vector manipulation. I don't think there is built-in support in Python to get what you want. However using simple trigonometric functions you can calculate normalize and perpendicular pretty easily using the built-in math module.
I recommend taking a look at the numpy package. It has many built-in fast math operations. You can use norm and cross as starting points for
Normalize
andPerpendicular
, respectively.