Hi, i'm a beginner and i try to build a 2D Game using <canvas> element and JavaScript.
I create a map and a character.. now, i use the keyboard to move a character in the map, but i have many question.
What is the theory for collisions and event?
I build a map so:
var map = {
[0, 0, 0],
[0, 1, 1],
[0, 0, 1]
}
For example, 0 is water, and 1 is grass. My class render the canvas with this matrix, associating the values with the images.
The problem is: my character, walking in the water!
Should I create a new matrix? For example:
var map = {
[{0, event}, {0, event}, {0, event}],
[{0, event}, {1, event}, {1, event}],
[{0, event}, {0, event}, {1, event}]
}
...is the correct way?
I don't find any tutorial for solve this problem!
AABB collision detection is pretty straight forward.
You just check if object A is "inside" of object B, and if so, take according action.
What you want to be careful of though is to not iterate through more tiles then you need to. It's a waste of RAM and not needed, you only want to check vs the adjuncent tiles, in other words, only the tiles that your character have any chance of colliding with.
Something like: var startx = entity.x / tilewidth;
var endx = entity.x / tilewidth + entity.w;
var starty = entity.y / tileheight;
var endy = entity.y / tileheight + entity.h;
for (var y = starty; y <= endy; y++)
{
for (var x = starx; x <= endx; x++)
{
if (map[y][x].type === collidable)
{
// do something fun :-)
}
}
}
I am at work now but this psuedocode should hopefully get you started
Edit* also, I'm unsure of what events you are reffering to outside of collisiondetection but you should be able to invoke any event you want in the loop. Also you can adjust start and end x/y choords if need be.
Next question, i create a class Tile and class Item.
Tile {
this.with;
this.height;
this.item = new item;
}
Item {
this.with;
this.height;
this.x;
this.y;
}
So, collidable == true if the next position of my character is in the item's area.
Example:
The tile represents grass with one rock; the rock is a Item().
[color=#666600]Then you code it so that when trying to move to a tile that isn't walkable the game prevents you. When entering a title if it has a valid eventId it calls that event from a global event list. Like wise if there is an item in that tile you can pick it up moving from the tile into the characters inventory. I wouldn't worry about having sizes in there for now and just make everything 1 tile in size. Larger objects and areas can be made by having parts assigned to different tiles. so a lake might be made up for 5 tiles, but each tile only knows about itself.