Page 3 of 3

Re: 3D fundamentals snake

Posted: July 1st, 2017, 10:11 am
by albinopapa
There is move constructed and move assigned.

move constructed
std::vector<int> myIntsA{ 1, 2, 3, 4, 5};
std::vector<int> myIntsB = { 123, 234, 345, 456 };

move assigned
myIntsA = {100, 200, 300, 400};
myIntsB = std::move( myIntsA };

When you make a new vector and initialize it by passing it to a function, it is only created once.
void DoVectorStuff( std::vector<ints> MyIntVec );

// This will cause myIntsA and all the elements in it to be copied to MyIntVec
DoVectorStuff( myIntsA );
// This will cause a new vector to be created as a temporary and the temporary is used as MyIntVec
DoVectorStuff( std::vector<int>{1,2,3,4,5} );

Code: Select all

#pragma once
template<typename T>
class Vector3
{
public:
	T x, y, z;

	Vector3() = default;

	Vector3( T x, T y, T z )
		:
		x( x ), y( y ), z( z )
	{};

	float dot( Vector3& v )const
	{
		return ( x * v.x ) + ( y * v.y ) + ( z * v.z );
	}

	float length()const
	{
		return sqrt( dot( *this ) );
	}

	Vector3 normalise() const
	{
		return *this * ( 1.f / length() );
	}

	Vector3 cross( Vector3& v )const
	{
		return {
			( y * v.z ) - ( z * v.y ),
			( z * v.x ) - ( x * v.z ),
			( x * v.y ) - ( y * v.x )
		};
	}

	Vector3 &operator+=( const Vector3 &V )
	{
		x += V.x;
		y += V.y;
		z += V.z;
		return *this;
	}

	Vector3 &operator-=( const Vector3 &V )
	{
		x -= V.x;
		y -= V.y;
		z -= V.z;
		return *this;
	}

	Vector3 &operator*=( const float S )
	{
		x *= S;
		y *= S;
		z *= S;
		return *this;
	}

	Vector3 operator+( const Vector3 &V )const
	{
		return Vector3( *this ) += V;
	}

	Vector3 operator-( const Vector3 &V )const
	{
		return Vector3( *this ) -= V;
	}

	Vector3 operator*( const float S )const
	{
		return Vector3( *this ) *= S;
	}

	Vector3 lerp( const Vector3 &V, const float Weight )const
	{
		return *this + ( ( V - *this ) * Weight );
	}

	T get(int i) 
	{
		switch (i)
		{
		case 0: return x;
		case 1: return y;
		case 2: return z;
		}
		return x;
	}

	void set(int i, T val) 
	{
		switch (i)
		{
		case 0: x = val;
		case 1: y = val;
		case 2: z = val;
		}
	}

	Vector3<int> toInt() 
	{
		return{ (int)x, (int)y, (int)z };
	}

	Vector3<float> toFloat() 
	{
		return{ (float)x, (float)y, (float)z };
	}
};

typedef Vector3<float>	Vec3f;
typedef Vector3<int>	Vec3i;
See if this helps any.

Re: 3D fundamentals snake

Posted: July 16th, 2017, 4:04 pm
by chili
Well I finally built this one and gave it a spin. Very sexy stuff. I like the way the snake segments pulse when you grow, and the animation on the food. The seams between triangles make me a little sad though ;D

I'll probably put this into an update video next time I do one of those. Thanks for sharing!