Adding sprite in Phaser js - javascript

I need to know how to add the 2nd, 3rd, 4th rows of this sprite image for the left, right and upwards(top) movement correspondingly.
Below code is for bottom movement and as its the first row in sprite, I am able to move it.
If I a create a long sprite horizontally I can achieve it, is there any other way?
Please help me figure out how to include the 2nd row onwards.
Sprite image (user/player) :
function preload(){
myGame.load.spritesheet('user', 'user4.png', 95, 158, 12);
}
var player;
function create(){
player = myGame.add.sprite(500, 100, 'user');
myGame.physics.arcade.enable(player);
player.animations.add('bottom', [0,1,2,3,4,5,6,7,8,9,10,11], 12, true, true);
}
function update(){
if (cursors.left.isDown) {
// Move to the left
player.body.velocity.x = -150;
player.animations.play('left');
}
else if (cursors.right.isDown)
{
// Move to the right
player.body.velocity.x = 150;
player.animations.play('right');
}
else if (cursors.up.isDown)
{
// Move to the right
player.body.velocity.y = -50;
player.animations.play('top');
}
else if (cursors.down.isDown)
{
// Move to the right
player.body.velocity.y = 50;
player.animations.play('bottom');
}
}

Just define the extra animations the way you've done for bottom:
player.animations.add('bottom', [0,1,2,3,4,5,6,7,8,9,10,11], 12, true, true);
player.animations.add('left', [12,13,14,15,16,17,18,19,20], 12, true, true);
player.animations.add('right', [21,22,23,24,25,26,27,28,29], 12, true, true);
And so on. Obviously I've just guessed the frame numbers above, you'll need to correct them to be whatever you actually need. But once you've done this, you can just call play on the animation keys.

Change preload to this:
function preload() {
game.load.spritesheet('user', 'user4.png', 95, 158, 48);
}
and add animation for all directions:
player.animations.add('bottom', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 12, true, true);
player.animations.add('left', [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], 12, true, true);
player.animations.add('right', [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], 12, true, true);
player.animations.add('top', [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47], 12, true, true);
Also remember to capture cursor inputs in your create() function:
cursors = game.input.keyboard.createCursorKeys();
Tested it and made it work. Sprite sheet is not 100% correct, but it looks ok.

to make things easy my approch is:
animation_arr = ['idle', 'walk', 'jump', 'idle_towel', 'walk_towel', 'jump_towel' ];
for(var i=0; i < animation_arr.length; i++){
player.animations.add(animation_arr[i], [0+(i*10), 1+(i*10), 2+(i*10), 3+(i*10), 4+(i*10), 5+(i*10), 6+(i*10), 7+(i*10), 8+(i*10), 9+(i*10)], 10, true);
}

Related

misunderstanding and questions around arrays and key pressed functions

My aim is to hook up a midi device to my computer to create and manipulate shapes in p5.js. I'm still learning code so have a few questions regarding arrays and keys.
Is there a way to say if any of the values in noteC, noteE and noteG are triggered then 'something happens'?
But in a sort of combo as that is a chord as a opposed to say noteD and noteE which is not a chord.
Essentially I am trying to manipulate the shapes via chords being played but I am unaware of if "noteC + noteE + noteG" would do anything.
For example:
var noteC = [24, 36, 48, 60, 72, 84, 96, 108]
var noteE = [28, 40, 52, 64, 76, 88, 100]
var noteG = [31, 43, 55, 67, 79, 91, 103]
function keyPressed();
if (value ===noteC, noteE, noteG) {
ellipse(200, 200, 25, 30);
ellipse(200, 200, 50, 60);
ellipse(200, 200, 100, 100);
To do it without chords I imagine it would go something like:
function keyPressed() {
if (value ===36) {
ellipse(200, 200, 25, 30);
} else if (value === 40) {
ellipse(200, 200, 50, 60);
}
}
However manually transforming shapes separately away from any combination of chords feels static and I would like there to be a relationship between the manipulation if a chord is being played.
I would like it so that the scale of the ellipse is determined by the velocity of the keys being played but if it is part of a chord the x and y parameters will be the same.
Not asking for someone to do the code but if anyone could help me understand or point me in the right direction that would be great!
Thanks!

Position dynamic shapes at same position

When I click on button each time it gives a different shape.All the shapes are dynamic. It can be polygon or circle (hundreds of shapes).
The shape is formed by group of lines.
The issue here is each shape gets positioned at different place and get scaled smaller then the other.I want them to be normalized. All the shapes should have proper scaling effect and positioned at same x position. Some of the shapes come in center , some go a bit towards top left.
Code with same transform matrix and scale is shown below.Shapes get positioned differently.May be the problem is coordinates of line.In the first code snippet it starts at (0,0) and last shapes line start at (15,5)
Can I give the group g positioned at same position for all shapes.Should I place relative to something?
var draw = SVG('drawing').viewbox(0, 0, 400, 400).attr("preserveAspectRatio", "xMidYMid meet");
var group = draw.group().translate(90, 90).scale(3)
var obj = {
"type": "Polygon",
"coords": [
[
[0, 0],
[30, 0],
[30, 20],
[60, 20],
[60, 40],
[0, 40],
[0, 0]
],
[
[0, 0],
[10, 50],
[50, 10],
[0, 0]
],
[
[0, 0],
[60, 0],
[80, 40],
[0, 40],
[0, 0]
],
[
[0, 0],
[50, 0],
[50, 20],
[0, 20],
[0, 0]
],
[
[50, 10],
[40, 40],
[20, 40],
[10, 20],
[50, 10]
],
[
[15, 5],
[40, 10],
[10, 20],
[5, 10],
[15, 5]
],
[
[20, 35],
[10, 30],
[10, 10],
[30, 5],
[45, 20],
[20, 35]
]
]
};
shapehandler()
function shapehandler() {
if (obj.coords.length) {
group.clear();
drawShape(obj.coords[0]);
obj.coords.shift();
}
}
function drawShape(coords) {
var lineCoords = [];
var pointListString = coords.toString();
var pointListArray = JSON.parse("[" + pointListString + "]");
for (let i = 0; i < pointListArray.length - 2; i += 2) {
let [x1, y1, x2, y2] = pointListArray.slice(i, i + 4)
lineCoords.push({
x1,
y1,
x2,
y2
});
}
lineCoords.forEach(function (lin, i) {
let colorShade = [
'#FFDC0B',
'#002438',
'#9B56BB',
'#c6c7e2',
'#318700',
'#fe854f',
'#FF8400',
'#31d0c6',
'#7c68fc',
'#61549C',
'#6a6c8a',
'#4b4a67',
'#3c4260',
'#33334e',
'#222138'
];
group.line(lin.x1, lin.y1, lin.x2, lin.y2).stroke({ color: colorShade[i], width: 4, linecap: 'square' });
});
}
html, body {
margin: 0;
padding: 0;
font-family: Arial;
}
svg {
width: 100%;
height: 100%;
}
#drawing{
margin: 20px;
display: inline-block;
position: relative;
border: 1px solid darkgrey;
overflow:hidden;
box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.js"></script>
<div id="toolbar">
<button type="button" id="btn-show-shape" onclick="shapehandler()">Show Polygon Shapes</button>
</div>
<div id="drawing">
</div>
I'm keeping your HTML.
The CSS is yours but I've added a rule for lines. It sets the stroke-width. For a nicer effect the stroke-linecap is round.
The most important: I'm using vector-effect:non-scaling-stroke. Since I don't know how much I will scale the group, I need vector-effect:non-scaling-stroke that causes an object's stroke-width to be unaffected by transformations and zooming.
In the javaScript I'm keeping all your data (points and colors), but I've rewrite the rest.
The most important thing; I'm calculating the scale which depends on the group's bounding box width. I'm translating the group in the center of the SVG canvas and scaling it.
I hope this is what you need.
const SVG_NS = 'http://www.w3.org/2000/svg';
const W = 400,cx = W/2;
const H = 400,cy = H/2;
let obj = {
type: "polygon",
coords: [
[
[0, 0],
[30, 0],
[30, 20],
[60, 20],
[60, 40],
[0, 40],
[0, 0]
],
[
[0, 0],
[10, 50],
[50, 10],
[0, 0]
],
[
[0, 0],
[60, 0],
[80, 40],
[0, 40],
[0, 0]
],
[
[0, 0],
[50, 0],
[50, 20],
[0, 20],
[0, 0]
],
[
[50, 10],
[40, 40],
[20, 40],
[10, 20],
[50, 10]
],
[
[15, 5],
[40, 10],
[10, 20],
[5, 10],
[15, 5]
],
[
[20, 35],
[10, 30],
[10, 10],
[30, 5],
[45, 20],
[20, 35]
]
]
};
let colorShade = [
'#FFDC0B',
'#002438',
'#9B56BB',
'#c6c7e2',
'#318700',
'#fe854f',
'#FF8400',
'#31d0c6',
'#7c68fc',
'#61549C',
'#6a6c8a',
'#4b4a67',
'#3c4260',
'#33334e',
'#222138'
];
// create a new SVG element
let svg = drawSVGElmt(
"svg",
{
viewbox:`0 0 ${W} ${H}`,
preserveAspectRatio:"xMidYMid meet",
},
drawing);
// create a group element
let group = drawSVGElmt(
"g",
{/*transform:"translate(90,90) scale(3)"*/},
svg
)
// draw a red dot in the middle of the canvas
drawSVGElmt("circle",{cx:cx,cy:cy,r:5,fill:"red"},svg)
let n = 0;
function drawAndScale(n){
//first remove all the lines from the group
while (group.firstChild) {
group.removeChild(group.firstChild);
}
// for all the points in obj.coords[n] draw a line
for(let i = 0, l = obj.coords[n].length -1; i < l; i++){
let p0 = obj.coords[n][i];
let p1 = obj.coords[n][i + 1];
let x1 = p0[0],y1 = p0[1];
let x2 = p1[0],y2 = p1[1];
let stroke = colorShade[i];
drawSVGElmt("line", {x1:x1,y1:y1,x2:x2,y2:y2,stroke:stroke}, group)
}
//get the size of the bounding box of the group
let BB = group.getBBox();
// set the scate using the width of the bounding box
let scale = (W * .75) / BB.width;
// scale & translate the group in the crnter of the SVG element
group.setAttributeNS(null,"transform",
`translate(${ scale * (-BB.x -BB.width/2)}, ${ scale * (-BB.y -BB.height/2)})
scale(${scale})
translate(${cx/scale}, ${cy/scale})`);
}
drawAndScale(n);
function shapehandler(){
if(n < obj.coords.length - 2){ n++; }else{n = 0};
drawAndScale(n);
}
// a function to draw an SVG element
function drawSVGElmt(type, o, _parent) {
let elmt = document.createElementNS(SVG_NS, type);
for (var name in o) {
if (o.hasOwnProperty(name)) {
elmt.setAttributeNS(null, name, o[name]);
}
}
_parent.appendChild(elmt);
return elmt;
}
html, body {
margin: 0;
padding: 0;
font-family: Arial;
}
svg {
width: 100%;
height: 100%;
}
#drawing{
margin: 20px;
display: inline-block;
position: relative;
border: 1px solid;
overflow:hidden;
box-sizing: border-box;
width:400px;
height:400px;
}
line{
stroke-width:50px;
stroke-linecap: round;
/* vector-effect:non-scaling-stroke causes an object's stroke-width to be unaffected by transformations and zooming */
vector-effect:non-scaling-stroke;}
<div id="toolbar">
<button type="button" id="btn_show_shape" onclick="shapehandler()">Show Polygon Shapes</button>
</div>
<div id="drawing">
</div>

Connecting data from 2 arrays

I have a little bit hard question, but I try to explain it:
So, I have 2 arrays. First array - array of cities. The second is the matrix with distances between this cities;
var cities = ['Gamburg', 'Dresden', 'Berlin', 'Bayern', 'Dortmund'];
var distanceMatrix = [
[0, 131, 523, 251, 600],
[131, 0, 785, 123, 541],
[252, 785, 0, 241, 741],
[251, 123, 241, 0, 632],
[600, 541, 741, 632, 0]
];
I need to generate a train with randomly choosen department and arrival point, with is not a problem. The problem is how to connect this 2 points with distance matrix correctly. If its possible. For example: distance between cities[1] and cities[3] accords to distanceMatrix[1][3] etc. So I need a function which randomly pick 2 towns and show distance between them according to distanceMatrix.
P.S. 2 days of hard mind work, and all I've done - is just 5 switch() functions, which is wrong way to complete this task.
Thank you !
You could take Array#indexOf for getting the index as accessor for the matrix.
var cities = ['Gamburg', 'Dresden', 'Berlin', 'Bayern', 'Dortmund'],
distances = [[0, 131, 523, 251, 600], [131, 0, 785, 123, 541], [252, 785, 0, 241, 741], [251, 123, 241, 0, 632], [600, 541, 741, 632, 0]];
function getDistance(city1, city2) {
return distances[cities.indexOf(city1)][cities.indexOf(city2)];
}
console.log(getDistance('Dresden', 'Berlin'));
console.log(getDistance('Dortmund', 'Bayern'));
An advanced solution could use an object with the indices.
var cities = ['Gamburg', 'Dresden', 'Berlin', 'Bayern', 'Dortmund'],
indices = { Gamburg: 0, Dresden: 1, Berlin: 2, Bayern: 3, Dortmund: 4 },
distances = [[0, 131, 523, 251, 600], [131, 0, 785, 123, 541], [252, 785, 0, 241, 741], [251, 123, 241, 0, 632], [600, 541, 741, 632, 0]];
function getDistance(city1, city2) {
return distances[indices[city1]][indices[city2]];
}
console.log(getDistance('Dresden', 'Berlin'));
console.log(getDistance('Dortmund', 'Bayern'));
Well, if I understood the problem correctly, you look for a way to form and access the matrix.
Let's first see the problem as indexes.
var cities = ['Gamburg', 'Dresden', 'Berlin', 'Bayern', 'Dortmund'];
cities[0] = Gamburg, cities[1] = Dresden, and so on.
The question is how to pick to cities at random and return the distance between the two.
function randomCities() {
while(true)
{
//Let's generate a random number between 0 and 4.
var randomCity_A = Math.floor((Math.random() * 4) + 0);
var randomCity_B = Math.floor((Math.random() * 4) + 0);
// add a condition that cities are not the same
if ( randomCity_A != randomCity_B){
var distance = distanceMatrix[randomCity_A][randomCity_B];
return "Distance between " + cities[randomCity_A] +" and " +
cities[randomCity_A] +": "+distance;
}
}
}
console.log(randomCities());
console.log(randomCities());

How can I get mouseClick to find a variable and randomize it?

Im working my way through the Khanacademy site and a a bit confused on how to make randomly sized(within certain parameters), and colored fish after mouseClick. I cant even get mouseClick working.
background(89, 216, 255);
var mouseClicked = function(drawFish){
};
^^^^^^^^^^^^^^^ What am I missing here? ^^^^^^^^^^
var drawFish = function(centerX, centerY, bodyLength, bodyHeight, bodyColor, tailWidth,
tailHeight, eyeColor,tailColor, eyeWidth, eyeHeight){
noStroke();
fill(bodyColor);
// body
ellipse(centerX, centerY, bodyLength, bodyHeight);
// tail
fill(tailColor);
triangle(centerX-bodyLength/2, centerY,
centerX-bodyLength/2-tailWidth, centerY-tailHeight,
centerX-bodyLength/2-tailWidth, centerY+tailHeight);
// eye
fill(eyeColor);
ellipse(centerX+bodyLength/3, centerY, eyeWidth, eyeHeight);
};
drawFish(296, 281, -57,52, color(245, 227, 30),-15, 60,color(13, 12, 12),color(66, 58, 58),4,4); // yellowFish
drawFish(290, 80, 180, 140, color(255, 0, 0), 57, 45,color(46, 66, 194), color(255, 204, 0),32,8); // redFish
drawFish(146,233, 218, 141, color(62, 110, 67), 30, 10, color(245, 240, 245), color(0, 51, 255),12,48); // greenFish
drawFish(233, 370, 322, 36, color(133, 34, 199), 61,15, color(255, 0, 0), color(34, 255, 0),67,20); // purpFish
Any other pointers or recommendations would be greatly appreciated.
Thanks guys!
Cool fishes! I'm learning Processing too. I ran your code and came up with this function for having random fishes appear when you click.
void mouseReleased() {
var c1 = color(random(0,255),random(0,255),random(0,255),random(0,255))
var c2 = color(random(0,255),random(0,255),random(0,255),random(0,255))
var c3 = color(random(0,255),random(0,255),random(0,255),random(0,255))
var s1 = random(10,100)
var s2 = random(10,100)
var s3 = random(10,100)
var s4 = random(10,100)
var s5 = random(5,s1)
var s6 = random(5,s2)
drawFish(mouseX, mouseY, s1, s2, c2, s3,s4, c2, c3,s5,s6); //randFish
}
To make an animation, I think you will want to use the draw() function, use variables for the x,y locations and redraw the background each time. This example has the red fish follow the mouse around.
void draw(){
background(89, 216, 255);
drawFish(mouseX, mouseY, 180, 140, color(255, 0, 0), 57, 45,color(46, 66, 194), color(255, 204, 0),32,8); // redFish
}
I hope your aquarium comes out really great!

How can I add keycontrol with createjs? I want to slide the container and background with arrow keys

stage.addChild(background);
stage.addChild(container);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
background.x-=1;
container.x-=2;
stage.update();
}
background and container contains large images more than the width of canvas so that it gives a parallax effect for the game.
If you want to be able to move them with w a s d or arrow keys or whatever you want, there's this file I like to use. (I recommend saving it in another document)
var Key = {
_pressed: {},
preventedDefaults:[32, 37, 38, 39, 40, 16, 90, 81, 68, 83, 87, 65],
Z: 90,
Q: 81,
D: 68,
S: 83,
W: 87,
A: 65,
SPACE: 32,
LEFT: 37,
UP : 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
isDown: function(keyCode){
return this._pressed[keyCode];
},
onKeyDown: function(e){
this._pressed[e.keyCode] = true;
if(this.preventedDefaults.indexOf(e.keyCode) > -1){
e.preventDefault();
}
},
onKeyUp: function(e){
delete this._pressed[e.keyCode];
}
}
window.addEventListener('keyup', function(e){Key.onKeyUp(e);}, false);
window.addEventListener('keydown', function(e){Key.onKeyDown(e);}, false);
So as you can see the numbers in the array preventedDefaults are the numbers of the keys on your keyboard which you can look up on google if you need other key codes.
To use it, you do it with a simple if statement like so:
if(Key.isDown(Key.DOWN) || Key.isDown(Key.S)){
move down or whatever
};
(make an if statement for each direction you want to be able to go)
As you can see you can use multiple keys for the same movement , so you can use the arrow keys and w a s d for example.
I hope this was clear enough. If not, ask away.

Categories

Resources