I am trying to create multiple hitbox areas in my game, but I can't find any documentation or examples of how to work with them.
The scenario is, my "Hero" have 2 hitbox, one on his feet and another on his body. If he hits an enemy with the foot hitbox, the enemy dies. If he hits the enemy with his body, his health have to be decreased.
How can I identify which hitbox create the collision event?
The answer to this question is similar to one recently answered on Crafty's forum.
You can attach invisible entities to a parent entity, which will move alongside the parent entity and simultaneously serve as hitboxes for your parent entity. In response to detecting collisions on these child entities, you can inform the parent entity about those collisions. There may be other ways to achieve the same thing.
Following is a small example that showcases the principle.
Use WASD to move, observe the color change depending on which body part touches the brown enemy.
Note that it doesn't resolve the case when both body parts are colliding with the enemy. Triggering events on the parent entity was reduced to directly modifying the parent entity for simplicity. onHit has its limitations and is used here for simplicity.
Crafty.init();
var hero = Crafty
.e("2D, DOM, Color, hero, Fourway")
.attr({x: 0, y: 0, w: 64, h: 128})
.color('gray')
.fourway();
var body = Crafty
.e("2D, Collision, WiredHitBox, body")
.attr({x: 0, y: 0, w: 64, h: 96})
.onHit('enemy', function() {
this._parent.color('red');
}, function() {
this._parent.color('gray');
});
var feet = Crafty
.e("2D, Collision, WiredHitBox, feet")
.attr({x:0, y: 96, w: 64, h: 32})
.onHit('enemy', function() {
this._parent.color('green');
}, function() {
this._parent.color('gray');
});
hero.attach(body);
hero.attach(feet);
Crafty.e("2D, DOM, Color, enemy")
.attr({x: 150, y: 96, w: 32, h: 32})
.color('brown');
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty-min.js"></script>
Related
I have spent hours reading and trying solutions to other people's wrapping problems and nothing is working.
I am using Crafty to build a game and want to display one line of instructions but no matter how I style the text it keeps wrapping at every space. If I take the spaces out, the whole sentence displays on one line. With spaces, each word is on its own line. I have tried float & white-space, align: justify, changing the coordinates, changing the font size, you name it. I am working in the JavaScript, not HTML. TIA
Here is what I have:
var helloWorldText = Crafty.e('2D, DOM, Text')
.attr({
x: 350,
y: 10
});
helloWorldText.text("Click on the matching character.");
helloWorldText.float(left);
helloWorldText.whiteSpace(nowrap);
helloWorldText.textColor('black');
helloWorldText.textFont({
size: '14px',
textAlign: justify
});
Setting a width (w) should allow your text to not wrap.
For example:
var helloWorldText = Crafty.e('2D, DOM, Text')
.attr({
x: 10,
y: 10,
w: 400
});
helloWorldText.text("Click on the matching character.");
helloWorldText.float(left);
helloWorldText.textColor('black');
helloWorldText.textFont({
size: '14px'
});
The "w" attribute comes from the CraftyJS 2D Component
When trying to position a shape in Konva you can use the .position() function and you use coordinates like in most 2d graphics stuff an inverted y grid so 100, 100 would be right 100px and down 100px.
BUT! when using .position() on the stage object you seem to get very strange effects where you (unlike any grid i've ever encountered) get an inverted x grid so that 100, 100 would be left 100px and up 100px
I haven't worked that much with 2d graphics so i might be missing something obvious but the documentation for stage.position() says get/set node position relative to parent and that it's inherited from Konva.Node#position Exactly the same as is said on shape.position() documentation. Is it that stage doesn't have a parent so it behaves differently? Or am i missing something else?
Example that shows how the positioning works on stage vs shape
https://jsfiddle.net/uvp3k6wy/
They work exactly the same.
The node.position() will define "where we need to draw a node".
stage.position({x: 50, y: 50}); means that all nodes that stage has will be drawn from {x: 50, y: 50} position on canvas. So whole stage is moved by 50, 50 px to right-bottom direction.
If you have a red circle in {x: 0, y: 0}, it will have an absolute position {x: 50, y: 50} because it is moved my stage position.
I'm using the html5 quintus js game library. According to
http://www.html5quintus.com/guide/sprites.md#.Va7FBPmznN4
the p.z can be used to change a sprite's stacking order. But it doesn't seem to do anything for me. I have insert multiple sprites in the same scene. My sprite is setup as this:
Q.Sprite.extend("test", {
init: function(p) {
this._super(p,{
asset: "smallship_1x2.png",
x: 150,
y: 300,
z : 0,
dragging : false,
offSet : {
x:0,
y:0
}
});
this.on("drag");
},
drag: function(touch) {
this.p.dragging = true;
this.p.x = touch.origX + touch.dx;
this.p.y = touch.origY + touch.dy;
this.p.z = 10;
}
});
I added a few of the test sprites in the same stage, when I drag a sprite, i want it to have higher stacking order (so the sprite will appear to be on top of others in case i drag across other sprites), however it seems that setting the p.z doesn't do anything. I've tried initializing the sprite with higher number on the z property but it also doesn't do anything, the stacking order seems to be solely based on the order that I insert them into the stage. (the last insert has the highest stacking order).
Does anyone know how to dynamically change the stacking order of sprites?
Any help is appreciated!!
Alright, I'm at my wits end and I can't get CraftyJS to do a tween.
So what I wanna do is, everytime a Mushroom gets hit, I want to check if that mushroom has the component "Answer". If it exists, I will do nothing. Otherwise, I wanna display a big red box that fades away.
Crafty.c("Mushroom", {
init: function() {
this.addComponent("collision");
this.collision();
this.onhit("bullet",function(e) {
this.destroy();
e[0].obj.destroy();
if(!this.has("Answer")) {
Crafty.e("2D, Tween, color, canvas")
.attr({alpha: 1.0, x: 170, y: 100, w:300, h:100})
.color("red")
.bind("enterframe", function() { //How do i actually get the box to fade?
this.tween({alpha: 0.5, x: 170, y: 100}, 30);
});
}
});
}
You are binding the tween code execution to the EnterFrame event, which will cause the tween to start with each frame. Instead, you want to simply call the tween function on the entity you created, like so
Crafty.e("2D, Tween, color, canvas")
.attr({alpha: 1.0, x: 170, y: 100, w:300, h:100})
.color("red")
.tween({alpha: 0.5, x: 170, y: 100}, 600);
And the tween function will manage its own EnterFrame over the next 600 ms (30 frames), after which it will fire the TweenEnd event.
(In old versions of Crafty, you specified the duration in frames instead of ms.)
This is more like a meta answer :-)
First, i would encourage you to upgrade to the latest version as it has a lot of bugfixes. Some of the changes you will have to do to get your code to run under the new release is to change all components and events to Pascal casing. That is enterframe => EnterFrame, canvas => Canvas etc.
Second, i think you should bring these questions to the Crafty forum to get the right audience. The only way i discovered this question was through a google alert.
The best way to get help is to create a jsfiddle from this template http://jsfiddle.net/mCdUX/62/ with a small running example demonstrating the part that you can not get to work.
Oh, and welcome to the Crafty community :-)
I want to create a jQuery plugin that implements a virtual HTML5 Canvas, i.e. a canvas that is physically no larger (or not much larger) that its appearance on the page. But the contents of what is intended to be shown on the canvas may be many times larger that the canvas and will be dynamically redrawn on depending on scrollbars.
You would think that this is very common functionality, but so far i have not been able to find examples either with jQuery plugins or otherwise. This is very similar to what e.g. SlickGrid does for a Div, except this is with a Canvas. I can think of two solutions:
Use a jQuery UI Slider to implement a scrollbar as a completely separate element and use its event to control the Canvas redrawing.
Do whatever it is SlickGrid does for the Div. It appears to make a Div that is slightly larger than what is being displayed and the hook up to scroll events to dynamically add/remove element to/from the Div. But I can't see how it modifies the scrollbar to make it appear as if there is much more in the Div that what is currently being displayed.
What would you recommend? Sample code would be greatly appreciated.
I dug into the SlickGrid code and used method 2) (sort of) - it was something like this I had in mind:
/*
jensk#migselv.com
Simple virtual CANVAS controlled by a native scrollbar made with two DIVs
Uses jCanvas by Caleb Evans (http://calebevans.me/projects/jcanvas/index.php)
Thanks to Michael Leibman of SlickGrid fame for ideas.
Still need to clean it up (get rid of hardcoded values) and make it a nice, configurable
jQuery component.
Currently also redraws the entire canvas on each scroll event. Could be optimized to
do real browser scrolling and only redrawing the needed parts.
Another gotcha is that since it is the zero width DIVs that causes the scroll events,
mouse wheel, trackpad, touchscreen etc. scrolling over the Canvas will not work - only
the scrollbar is active. To solve this, one could make the Canvas larger inside a
smaller DIV too, catch scroll events from it and perform redrawing and setting the DIV's
scrollTop accordingly.
*/
var h = 10000; // virtual canvas height
var vp = 400; // viewport height
var viewport, fakescrolldiv, canvas;
function onScroll() {
var scrollTop = viewport.scrollTop();
console.log("onScroll scrollTop=" + scrollTop);
$("canvas").clearCanvas();
// Red box top
$("canvas").drawRect({
fillStyle: "#F00",
x: 150,
y: 20 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
// Green box middle
$("canvas").drawRect({
fillStyle: "#0F0",
x: 150,
y: 140 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
// Blue box bottom
$("canvas").drawRect({
fillStyle: "#00F",
x: 150,
y: 260 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
var i = 0;
for (i = 0; i <= 396; i++) {
$("canvas").drawLine({
strokeStyle: "#000",
strokeWidth: 1,
x1: 0,
y1: i,
x2: (scrollTop + i) % 50,
y2: i
});
if ((scrollTop + i) % 50 === 0) {
$("canvas").drawText({
fillStyle: "#729fcf",
text: (scrollTop + i).toString(),
align: "left",
baseline: "top",
font: "normal 12pt Verdana",
x: 60,
y: i
});
}
}
}
$(function() {
viewport = $("#viewport");
fakescrolldiv = $("#fakescrolldiv");
canvas = $("#gfx");
viewport.css("height", vp);
fakescrolldiv.css("height", h);
viewport.scroll(onScroll);
viewport.trigger("scroll");
});
Live demo
Any suggestions for improvements or simplifications are greatly appreciated.
From my personal experience your option (1) is an attractive choice, but there might be some interesting points in making it into a useable jQuery plugin.
I've been working on a financial data visualisation system that explicitly uses HTML5 Canvas for graph and chart drawing. We have different virtual 'scenes' or 'slides' in the canvas which 'slide in' and 'slide out' in the canvas, much like the same way you'd navigate in a big virtual canvas. All the event handling buttons are exclusively drawn on the canvas which dictate which screen we'd be showing, but we have a one/two normal HTML forms that take user inputs and brings those 'slides'. We use jQuery to handle events from these text boxes, but the jQuery codes are deeply nested inside the other Canvas drawing codes, (unlike an externalised call, which would be an idea candidate for making a plugin).
Sliding or updating the canvas is another thing. This is because not only it depends on the jQuery event that triggers the update but it also depends on the Canvas Framework (plain code or KineticJS, EaselJS, jCotton etc) that is responsible for the update. If you use a framework, you'll need to interface with the framework as well.
For simplicity let's assume that there is a callback function that you can call for that Canvas framework with parameters like movement offset (x, y), and the framework will add/remove this offset to the x and y positions of all the objects drawn in the canvas, most Canvas drawing frameworks also have a render() function that it calls periodically so that next time it draws the scene the results will automatically show (in your case, scrolling through the virtual canvas).
So it basically comes down to not only writing it as a jQuery plugin but also a binding it to a particular Canvas Framework e.g. KineticJS or others.
If you use basic Canvas functions instead of using any of those Frameworks, then it's another story, you can write your own render and update functions for the canvas, but in that case it'll be restricting the potential user to adhere the limitations of your drawing functions, unless you expose an API to extend them; but then again, that means you are writing your own Canvas framework :)
I'm not sure if I understood your problem correctly, in that case you can safely ignore my advice :), but If I'm right, my opinion would be: making a plugin like this would require also binding to a Canvas framework to make it really useable.
Hope it helps.