Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Post code

Name: Anonymous 2011-10-06 9:06

Any code you work with right now, and we'll criticize it(or not).

Name: Anonymous 2011-10-07 9:40

Hey /frog/

Please criticize my C++ 2D-vector class. Implementation in header file for inlining.


#ifndef VEC2_H_INCLUDED_
#define VEC2_H_INCLUDED_

#include <cmath>

/**
 * Represents 2D vector.
 */
class Vec2
{
public:
    float x, y;
    /** Construct vector with given values */
    Vec2(float _x, float _y) : x(_x), y(_y) {}
    /** Create uninitialized vector */
    Vec2(){}
    /** Construct scaled copy */
    Vec2(const Vec2& v, float scale_ratio) {
        *this = v;
        scale(scale_ratio);
    }
    Vec2& operator += (const Vec2& v) {
        x += v.x;
        y += v.y;
        return *this;
    }
    Vec2& operator -= (const Vec2& v) {
        x -= v.x;
        y -= v.y;
        return *this;
    }
    Vec2 operator + (const Vec2& v) const {
        return Vec2(x+v.x, y+v.y);
    }
    Vec2 operator - (const Vec2& v) const {
        return Vec2(x-v.x, y-v.y);
    }
    /** multiply with scalar */
    void scale(float m) {
        x *= m;
        y *= m;
    }
    /** Dot product */
    float dot(const Vec2& v) const {
        return x * v.x + y * v.y;
    }
    /** Cross product */
    Vec2 cross(const Vec2& v) const {
        return Vec2(y - v.y, x - v.y);
    }
    float length() const {
        return std::sqrt(length2());
    }
    /** Square of length */
    float length2() const {
        return x*x + y*y;
    }
    /** Distance to other vector */
    float distance(const Vec2& v) const {
        return std::sqrt(distance2(v));
    }
    /** Distance to other vector squared */
    float distance2(const Vec2& v) const {
        float dx = x - v.x;
        float dy = y - v.y;
        return dx*dx + dy*dy;
    }
    /** Normalize vector. The length after normalization is 1 */
    void normalize() {
        scale(1 / length());
    }
    /** set new value */
    void set(float _x, float _y) {
        x = _x;
        y = _y;
    }
    /** Rotate vector by angle radians */
    void rotate(float angle) {
        float len = length();
        angle += atan2(y, x);
        x = cos(angle) * len;
        y = sin(angle) * len;
    }
    /** Create vector projection: u projected to *this */
    Vec2 projection(const Vec2& u) const {
        Vec2 p = *this;
        float len = length();
        p.scale(this->dot(u) / (len * len));
        return p;
    }
};

#endif

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List