Jump to content

  • Log In with Google      Sign In   
  • Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

HappyCoder

Member Since 28 Apr 2007
Online Last Active Today, 05:03 PM
-----

#5060396 What's the best way to do this?

Posted by HappyCoder on 08 May 2013 - 02:36 PM

Don't make enemies inherit from a drawable object, rather you should have the enemy use a drawable object.

Make the enemy a subclass of an entity object, that other entity objects can then inherit from.

Use smart pointers in your vectors, the standard library has shared pointer you can use (shared_ptr). This way objects don't have to be copied everywhere.
class Entity
{
    std::shared_ptr<Drawable> drawable;
public:
    Entity(const std::shared_ptr<Drawable>& drawable);
};

class Enemy : Entity
{
public:
};

Now that you have separated your drawable class from your entity class you can change how an enemy is drawn simply by passing it a different drawable. Whenever the enemy moves or changes in any other way, it updates its corresponding drawable object. This may seem like extra work but in the end it is a much better design and will let your code be much more flexible and your project can continue to grow without coming apart at the seams.


#5059087 Html5 Canvas: Why in the following JSFiddle, the stroke rectangle full opacit...

Posted by HappyCoder on 04 May 2013 - 12:00 AM

It appears that it is your line width and the canvas seems to be off by half a pixel. When the width is increased to 2 the lines draw solid.

 

When the first two parameters of strokeRect are increased by 0.5 the lines draw correctly.




#5055003 opengl, init render to a texture problem

Posted by HappyCoder on 19 April 2013 - 02:05 PM

You use glFramebufferRenderbuffer to try to bind a texture to the frame buffer. You probably want to use glFramebufferTexture2D for that.

Also, you don't need to create the renderbuffer storage for depth. You already are using a texture for that.


#5054675 Starting on first game (mobile)

Posted by HappyCoder on 18 April 2013 - 01:31 PM

Honestly, I would pick a smaller project to start with. A 3D turn based RGP is quite an undertaking. On the surface it may appear to not be that complicated but in reality there is a lot of work that goes into a game, even with an existing game engine.

Start by making games like tetris, breakout, or something similar. Once you are getting the hang of that, start to move up. Make a 2D tile based game. This could be a simple platformer, or even the basics of an RPG. After working your way through a few of these games then Perhaps you could try your hand at the kind of game you are looking to do now.

If you are wanting to program just because you want to bring your great game idea to life then you probably aren't going to make it there. It is a long path but if you enjoy the actual programming aspect of it then you will enjoy the journey and over the years you will find your self an increasingly capable programmer. Once you reach a certain level of proficiency you will find yourself feeling free to make whatever you decide to put your mind and time towards but until you are there take smaller steps.


#5053608 Is this a bad programming paradigm?

Posted by HappyCoder on 15 April 2013 - 04:27 PM

There are definately better solutions.

 

If you need B to have some functionality that A contains, concider having B contain an instance of A that it uses internally

 

class A
{
    public void foo();
    public void bar();
}
 
class B
{
    private A a;
    public void foo()
    {
        a.foo();
    }
}

 

This way you can expose the needed functionality of A but impose any restrictions that B may have.

 

If you actually need B to be treated as an A concider making them both be derived from the same base class or same base interface.

class Base
{
    public void foo();
}
 
class A : public Base
{
    public void foo();
    public void bar();
}
 
class B : public Base
{
    public void foo();
}

 

This way you can put any common functionality in the Base and each A and B can then apply their own restrictions or add any additional methods.




#5048040 Help rotating a sprite D3D9

Posted by HappyCoder on 29 March 2013 - 10:54 AM

It looks like you need to reset the transformation after each draw call.
void Draw(LPD3DXSPRITE sprite, LPDIRECT3DDEVICE9 d3dDevice)
{
        D3DXMATRIX identity;
        D3DXMatrixIdentity(&identity);
	sprite->SetTransform(&identity);
	sprite->Draw(texture, &enemy, &D3DXVECTOR3(0, 0, 0), &D3DXVECTOR3(400, 400, 0),                D3DCOLOR_ARGB(255,255,255,255));
	sprite->SetTransform(&matrix);
	sprite->Draw(texture, &guy, &D3DXVECTOR3(0, 0, 0), &guyPosition, D3DCOLOR_ARGB(255,255,255,255));
}



#5045315 appendChild() and removeChild() problems in JS

Posted by HappyCoder on 21 March 2013 - 11:29 AM

A trick you can do in javascript is wrap everything in a single function and that takes them all out of the global scope.

So lets say you have all of the following global variables declared as such.
var a = 0;
var b = 1;

function doStuff()
{
    ++a;
}
...
You can wrap that code like this
function GameOne()
{
   var a = 0;
   var b = 1;

   function doStuff()
   {
       ++a;
   }
   ...
}
Now all of those variables are local variables to a function so there will be no conflicts. Then to run the code you simply call the function.
GameOne();
If you want to jump between games you will have to ensure that the first game you are coming from cleans up its event listeners and that its game loop exits.

This hack would seem to be a quick solution to your current problem, although I wouldn't recommend this solution for any new projects you start. Doing it this way requires you to reimplement your game loop and other code in every source file. Ideally you want to get rid of any duplicate code.

And if you need to get any local variables you can add a getter.
function GameOne()
{
   var a = 0;
   ...

   GameOne.getA = function()
   {
      return a;
   }
}
Then to use the getter you simply call GameOne.getA().


#5044933 appendChild() and removeChild() problems in JS

Posted by HappyCoder on 20 March 2013 - 10:49 AM

I would have to confirm this but I would think that even after removing the script tag the code in it would still be defined and would continue to run. Also, trying to rely on loading and unloading a source file to control behavior sounds a little shaky to me. I would search for a way to load all of your source at the beginning then have another way to control what code is active.

I am assuming you are using the same names for functions in the different source files, so loading both at the same time would cause conflicts. If that is so the following might work well for you.

game.js
// create the game one object
var GameOne = {}

// add all the functions for game one into 
// the GameOne object
GameOne.updateGame = function(){
  ctxBg.drawImage(startmeny, 0, 0); 
}

// then add these
GameOne.becomeActive = function() {
   // add event listeners, or do other game setup
}

GameOne.resignActive = function() {
   // remove event listeners, do any cleanup
}

game2.js
// do the same thing for game two, only with whatever logic you want there
var GameTwo = {}
GameTwo.updateGame = function(){
   // game logic
}
GameTwo.becomeActive = function() {
   // add event listeners, or do other game setup
}

GameTwo.resignActive = function() {
   // remove event listeners, do any cleanup
}
Now each game is defined in a separate object so in your main game loop code you could have something like this
var activeScene = null;

function setActiveScene(game)
{
    // tell the active game it is going away
    if (activeScene)
        activeScene.resignActive();

    activeScene = game;

    // alert the active game it is now active
    if (game)
        game.becomeActive();
}

// set the starting scene
setActiveScene(GameOne);

function loop() {
     // update the active game
     activeScene.updateGame();  
     requestAnimFrame(loop);
}

I would give more meaningful names to your GameOne and GameTwo object. I just used those names for this example. Perhaps something like MainMenu, Level1, ect... Then whenever you want to change to another scene you simply call setActiveScene(Level1)


#5038585 How to set a timer in JavaScript?

Posted by HappyCoder on 02 March 2013 - 06:52 PM

Well, I profiled your code using google chrome. If you don't know this feature this is an excellent time to learn it. It tells you where your code spends the most time. You use it by opening up the developer tools, clicking on the profiles tab, then select the javascript cpu profile. Run the profiler then go ahead and play your game normally. After a short time stop the profiler and it will show you where your code spends the most time. This is what I found

60.62% of the time your programming is running in the Jet.collision method. It seems you are doing collision on 525 bullets against 125 enemies. This is 65625 total checks. Speeding that up would give you the most benefits. Consider only updating the bullets or enemies on screen. That would greatly reduce the amount of work needed. But 65625 really isn't a very large number. It shouldn't be slowing down your game as much as I have seen.

I think the problem you are running into is that you are setting init to be the load callback for all of your images. That means every time an image is loaded, it calls init and init calls loop. You have 15 game loops running at the same time. Your set timeout interval is only 100, that means for a single game loop you have about 10 frames per second. You have 15 game loops so your game is trying to do 150 frames per second.

So to fix it. You should keep track of how many images you have to load, store that number somewhere. Have your images use a different callback function. This function should subtract one from your pending image count. If it reaches 0 then you call init.
var pendingImages = 15;

var plane2 = new Image();
plane2.src = 'images/PlaneRight.gif';
plane2.addEventListener('load', imageLoaded, false);

var bullet = new Image();
bullet.src = 'images/Bullet.gif';
bullet.addEventListener('load', imageLoaded, false);
...

function imageLoaded()
{
    --pendingImages;
    if (pendingImages == 0)
    {
        init();
    }
}
Once you add this your game will probably run slow because it will be running at 10 frames per second instead of trying to pull 150. So you will have to increase the velocity of all the objects on screen and change the timeout time to be less for a faster framerate. I would personally use just requestAnimationFrame.

EDIT:
Also, looking over your code I noticed that you are using three different rendering contexts. I would recommend only using one.


#5035143 Calculating normals

Posted by HappyCoder on 21 February 2013 - 03:43 PM

As Paradigm Shifter pointed out, you need to make sure the vertices are consistently being wound the correct way. If you reverse the winding then the normal would be pointing the wrong way.

I would reccomend breaking up that normalizing code. It is hard to follow. I would create a seperate method for calculating normals to begin with.
void CalculateNormal(D3DXVECTOR3 *pOut, const D3DXVECTOR3 *pV1, const D3DXVECTOR3 *pV2, const D3DXVECTOR3 *pV3)
{
D3DXVec3Cross(pOut, &(*pV2 - *pV1), &(*pV3 - *pV1));
}
Then I would calculate the normals on each face and apply them to the vertices rather than having each vertex recalculate the normal of the adjacent faces.

So the steps.

Set all vertex normals to zero.
Loop through each face and calculate the normal, then add that normal to the normals of all vertices in that face.
Loop through all the vertices and normalize them.

You can normalize each face normal as you calculate them before adding them to the vertex normal. That will give each adjacent face equal weight in calculating the vertex normal. If you don't normalize them then faces with a larger surface area will have a greater influence on the calculated normal. Depending on what you want you can go either way. If the areas are roughly the same then it wont make much of a difference.


#5035059 Calculating normals

Posted by HappyCoder on 21 February 2013 - 11:35 AM

To calculate a normal for a single triangle you do the following.

x = cross(b - a, c - a)

where a, b, and c are points on the triangle and cross is the cross product of the two vectors.

Then to calculate a normal for a single point you simply sum up the normals for every face the point is part of then normalize it.


#5034652 Game Architecture/Design Pattern?

Posted by HappyCoder on 20 February 2013 - 12:27 PM

The more general you can make the core of your game the more flexible it will be. Also, you should try to minimize what certain classes know about each other. For small game projects this usually wont become an issue but as a game grows if your design has problems it will become very difficult to if you want to do something that Let me just point out a couple of things that I would reconsider in your design.

First, when I think of design and what objects know about each other, I like to think of it as a tree. Objects only know about their branches, but branches shouldn't know what object is their parent nor should they know about their sibling branches. This cannot be the case all the time but try to follow this as much as you can. So you may have a game manager class that knows about the enemies and the player but the they don't know about the game manager class nor do they know about each other.

Keeping that in mind your end game logic is handled in your enemy manager. Keep that logic in the game class. I would add a method to the EnemyManager that checks to see if all enemies are dead and returns a boolean instead of having the game manager check the integer value directly. Classes should not know about the internal workings of each other. They shouldn't access data members directly, instead they should interact through method calls.

I wouldn't have your enemies know about the player, rather I would create an interface, perhaps you could call it EnemyTarget. Add methods to the EnemyTarget interface such as getting the target location and whatever other information you need from it and have the player implement that interface, then when you create the EnemyManager you can pass it the player class, but the enemies don't know it is the player, they just know it as their target. This adds flexibility to your game and would allow enemies to target other objects, if you later decide you want to do that. Also, avoid the temptation of setting the player state and other data in the player class, rather use the interface to send method calls to the player and have the player handle updating its damage and state, for example.

interface EnemyTarget
{
    Point getPosition();
    void applyDamage(int amount);
    // anything else applicable here
}

class Player implements EnemyTarget
{
    Point getPosition()
    {
        return position;
    }

    void applyDamage(int amount)
    {
        hitPoints -= amount;
        if (hitPoints <= 0)
           status = PlayerStatus.Dead;
    }
}

class EnemiesManager
{
    EnemyTarget target;
}
Also, don't have your player modify the GameStatus, have the player only modify its own status and have the game manager check the player status and have it determine what to do from there. This would make it easier to change the behavior when the player dies.

Another point I would like to make is to separate the code that handles drawing, from code that handles collision detection, from the code that handles the game logic. It appears you are doing a text adventure so this may not directly apply but lets say for example we have a character in our scene. Rather then having that one character class have a draw, update, and collision detection code. Break them up. Create a scene graph where you can add objects you want to draw to it and that part of the code only handles drawing the scene. Then add a collision space where you can add objects for collision detection. Then you create a player class that ties these things together. The player class creates a sprite and inserts it into the scene graph, the player creates a collision shape and adds it to the collision scene. Then whenever you update, you ask the collision space for any contacts the player is making in the scene, update accordingly, then change the position of player in the scene graph and the collision space. The details of this can vary but the important thing is that you have separate parts of code that don't know about each other meaning you could take out that subsystem and have it work independently of the rest of the code.


#5034394 Camera movement

Posted by HappyCoder on 19 February 2013 - 09:09 PM

You could define different keyframes and interpolate between them. Each keyframe representing a position and rotation at a given point in time.

To interpolate between two points you simply use

x = a * (1 - t) + b * t

where a is your stating point, b is the ending point, and t is a value between 0 and 1. You could then keep track of how much time has passed and calculate t with timePassed / animationDuration. Once time passed is bigger than animationDuration, you end the animation and continue the camera normally.

How do you represent camera rotation? If you using euler angles you could interpolate the angles as seen above and should get a good result.


Also, a trick I have found that works really well for player or camera control state is using the state pattern. It works by implementing the differnt control logic states in separate classes, then you simply have a variable in the camera that you assign to change the camera control state. So for example
class CameraControlState
{
    abstract void update(Camera camera, double dt);
}

class FollowCameraControlState extends CameraControlState
{
    void update(Camera camera, double dt)
    {
        // logic for follow camera
    }
}

class AnimationCameraControlState extends CameraControlState
{
    void update(Camera camera, double dt)
    {
        // logic for animating camera
    }
}

class Camera
{
    CameraControlState controlState;

    void update(double dt)
    {
        controlState.update(this, dt);
    }
}

// then to use it somewhere in the code
Camera camera = new Camera();
camera.setControlState(new FollowCameraControlState(cameraTarget));

// then to start a cutscene
camera.setControlState(new AnimationCameraControlState(animationKeyframes));

Implementing that may be an overkill for you current project but I am throwing it out there for consideration. Doing the camera (and player) control like this makes it extremely flexible. You can add a first person view, a fixed camera, a top down camera, a follow camera, and any other idea you may have easily. Just add another class, you don't need to touch any of the camera code and you don't end up with monstrous switch statements everywhere in your code that are difficult to maintain.

Or a quick and dirty alternative to animating your camera could be to only allow your camera to move and rotate at a limited velocity and then start the camera far away and facing another direction.


#5031121 5x5x5 Chessboard in OpenGL

Posted by HappyCoder on 11 February 2013 - 11:50 AM

Here are a few things I think you should understand when building a 3D game.

First of all knowing 3D transformations is a must. Space and Matrix Transformations - Building a 3D Engine

This website has some good tutorials for starting opengl. NeHe I have heard somebody say these are a little outdated but I still feel they help out with learning the basics.

As for loading the pieces into your game. There is no standard format for loading into OpenGL, rather opengl supplies methods of drawing geometry that is very flexible. You are responsible for finding a way to getting the 3d model data into your game. With that being said I would recommend .obj files as being a good starting point. You should be able to export as an obj and may even find an existing obj loader online.


#5023248 High School Student with High Goals -- Need Advice

Posted by HappyCoder on 19 January 2013 - 12:59 PM

My suggestions. Do what you love. You may or may not get into Stanford and you aren't a failure if you don't. If you work hard and apply yourself you will find yourself in a university that is good for you and will help you along in your career. Be patient and don't worry if you feel like there are others who are better programmers than you. It always seems there is a bigger fish in the pond.

I think getting into Stanford is a good goal. That should help you stretch yourself and achieve more, but don't let that goal drain you or take away your happiness.

In my own life I worked on projects in during high school because I enjoyed doing it. I wasn't trying to impress anybody. I tried in school and I graduated with a 3.5. My highest score on the ACT was a 28 in math and everything else was above a 20. I still got into the school I wanted to and am satisfied with the direction my education and my career. The projects I spend the most time on are the ones I do because I enjoy them. These personal projects are usually more complicated then what I do in any of my CS classes and I find myself strolling through the programming projects where others in my class struggle. I think this is because my main focus is programming out of enjoyment. Not because my focus is get badges of honor.




PARTNERS