I'm very new with JS and Pixi.js and I want some advices, Below is my example code. I want to know How to separate code to main.js, boss.js as function? I try but it's not work stage is show but boss that i draw not show so, I want to know how to. Thank you
var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer();
document.body.appendChild(renderer.view);
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var circle = new PIXI.Graphics();
var rect = new PIXI.Graphics();
var rectWidth = 160;
var rectHeight = 200;
var boss = new PIXI.Container();
rect.lineStyle(0);
rect.beginFill(0xffdbac, 1);
rect.drawRect((screenWidth / 2) - (rectWidth / 2), (screenHeight / 2) - 60, rectWidth, rectHeight);
rect.endFill();
boss.addChild(rect);
circle.lineStyle(0);
circle.beginFill(0xffdbac, 1);
circle.drawCircle(screenWidth / 2, (screenHeight / 2) - 140, 80);
circle.endFill();
boss.addChild(circle);
stage.addChild(boss);
stage.interactive = true;
renderer.view.style.position = "absolute";
renderer.view.style.display = "block";
renderer.autoResize = true;
renderer.resize(screenWidth, screenHeight);
rect.lineStyle(0);
rect.beginFill(0xffdbac, 1);
rect.drawRect((screenWidth / 2) - (rectWidth / 2), (screenHeight / 2) - 60, 160, 200);
boss.addChild(rect);
circle.lineStyle(0);
circle.beginFill(0xffdbac, 1);
circle.drawCircle(screenWidth / 2, (screenHeight / 2) - 140, 80);
boss.addChild(circle);
stage.addChild(boss);
animate();
function animate() {
renderer.render(stage);
requestAnimationFrame( animate );
}
Here is an example of boss creation separated to it's own file and function:
http://plnkr.co/edit/43GgC3nPvFKEpflGhwvV?p=preview
main.js
document.addEventListener("DOMContentLoaded", function(event) {
var stage = new PIXI.Container();
var renderer = PIXI.autoDetectRenderer();
document.body.appendChild(renderer.view);
var screenSize = {
width: window.innerWidth,
height: window.innerHeight
}
var rectSize = {
width: 160,
height: 200
};
var boss = createBoss(screenSize, rectSize);
stage.addChild(boss);
stage.interactive = true;
renderer.view.style.position = "absolute";
renderer.view.style.display = "block";
renderer.autoResize = true;
renderer.resize(screenSize.width, screenSize.height);
boss = window.createBoss(screenSize, rectSize);
stage.addChild(boss);
animate();
function animate() {
renderer.render(stage);
requestAnimationFrame( animate );
}
});
boss.js
function createBoss(screenSize, rectSize) {
var circle = new PIXI.Graphics();
var rect = new PIXI.Graphics();
var boss = new PIXI.Container();
rect.lineStyle(0);
rect.beginFill(0xffdbac, 1);
rect.drawRect((screenSize.width / 2) - (rectSize.width / 2), (screenSize.height / 2) - 60, rectSize.width, rectSize.height);
rect.endFill();
boss.addChild(rect);
circle.lineStyle(0);
circle.beginFill(0xffdbac, 1);
circle.drawCircle(screenSize.width / 2, (screenSize.height / 2) - 140, 80);
circle.endFill();
boss.addChild(circle);
return boss;
}
Related
I looked at this example with three js to draw particles with images and works perfectly but i want to change the image with a switch when click a button (calls this function):
const changeImg = function(num) {
switch (num)
{
case 0:
imgData ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA....";
break;
case 1:
imgData = "data:image/png;base64,iVBORw0KGgoAAAAN..."
break;
}
img.src = imgData;
}
And works but when you click multiple times website becomes slow.
How can I update just the image without slowing down the website?
EDIT 1
I change the code like this:
var renderer, scene, camera, ww, wh, particles, mw, mh, mz, numState;
numState = 0;
mz = 6; // Matrerial size
ww = document.getElementById('map-container').offsetWidth,
wh = 450;
mw = ww * 2;
mh = wh * 2;
var centerVector = new THREE.Vector3(0, 0, 0);
var previousTime = 0
speed = 10
isMouseDown = false;
// Render
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("map"),
antialias: true
});
renderer.setSize(mw, mh);
renderer.setClearColor(0x12347C);
// Scence
scene = new THREE.Scene();
// Camera
camera = new THREE.OrthographicCamera( ww / - 2, ww / 2, wh / 2, wh / - 2, 1, 1000 );
camera.position.set(7, 0, 4);
camera.lookAt(centerVector);
scene.add(camera);
camera.zoom = 4;
camera.updateProjectionMatrix();
// Geometry
var geometry = new THREE.Geometry();
var material = new THREE.PointsMaterial({
size: mz,
color: 0xFFFFFF,
sizeAttenuation: false
});
// Particle
particles = new THREE.Points();
var getImageData = function(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height);
}
var drawTheMap = function() {
geometry.dispose();
particles.material.dispose();
particles.geometry.dispose();
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
var vertex = new THREE.Vector3();
vertex.x = x - imagedata.width / 2;
vertex.y = -y + imagedata.height / 2;
vertex.z = -Math.random()*500;
vertex.speed = Math.random() / speed + 0.015;
geometry.vertices.push(vertex);
}
}
}
particles.material = material;
particles.geometry = geometry;
scene.add(particles);
requestAnimationFrame(render);
};
var init = function() {
imagedata = getImageData(image);
drawTheMap();
onResize();
window.addEventListener('mousemove', onMousemove, false);
window.addEventListener('mousedown', onMousedown, false);
window.addEventListener('mouseup', onMouseup, false);
window.addEventListener('resize', onResize, false);
};
var onResize = function(){
var mov1, mov2;
ww = document.getElementById('map-container').offsetWidth;
wh = 450;
if (window.innerWidth > 850) {
mw = ww * 2;
mh = wh * 2;
mz = 6;
mov1 = 2.2;
mov2 = 1.9;
particles.material.size = mz;
} else {
mw = ww;
mh = wh;
mz = 3;
mov1 = 2;
mov2 = 2;
particles.material.size = mz;
}
renderer.setSize(mw, mh);
camera.left = ww / - mov1;
camera.right = ww / 2;
camera.top = wh / mov2;
camera.bottom = wh / - 2;
camera.updateProjectionMatrix();
};
var onMouseup = function(){
isMouseDown = false;
}
var onMousedown = function(e){
isMouseDown = true;
lastMousePos = {x:e.clientX, y:e.clientY};
};
var onMousemove = function(e){
if(isMouseDown){
camera.position.x += (e.clientX-lastMousePos.x)/100;
camera.position.y -= (e.clientY-lastMousePos.y)/100;
camera.lookAt(centerVector);
lastMousePos = {x:e.clientX, y:e.clientY};
}
};
var render = function(a) {
requestAnimationFrame(render);
particles.geometry.verticesNeedUpdate = true;
if(!isMouseDown){
camera.position.x += (0-camera.position.x)*0.06;
camera.position.y += (0-camera.position.y)*0.06;
camera.lookAt(centerVector);
}
renderer.render(scene, camera);
};
var imgData;
var image;
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
const changeState = function(state, num) {
document.getElementById('dropbox-choose').innerHTML = state;
numState = num;
switch (numState)
{
case 0:
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
break;
case 1:
imgData = "data:image/png;base64,iVBORw0KGgoI..."
break;
}
image.src = imgData;
}
image = document.createElement("img");
image.onload = init;
image.src = imgData;
And the THREE.WebGLRenderer is only applied once but when I click to change the image, it does not update and also I still have the problem that the website slows down
it's my first time using three js and i don't know if i'm applying well what it says in the documentation
EDIT 2
var renderer, scene, camera, ww, wh, particles, mw, mh, mz, numState;
numState = 0;
mz = 6;
ww = document.getElementById('map-container').offsetWidth,
wh = 450;
mw = ww * 2;
mh = wh * 2;
var centerVector = new THREE.Vector3(0, 0, 0);
var previousTime = 0
speed = 10
isMouseDown = false;
// Render
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById("map"),
antialias: true
});
renderer.setSize(mw, mh);
renderer.setClearColor(0x12347C);
// Scence
scene = new THREE.Scene();
// Camera
camera = new THREE.OrthographicCamera( ww / - 2, ww / 2, wh / 2, wh / - 2, 1, 1000 );
camera.position.set(7, 0, 4);
camera.lookAt(centerVector);
scene.add(camera);
camera.zoom = 4;
camera.updateProjectionMatrix();
// Geometry
//var geometry = new THREE.Geometry();
var material = new THREE.PointsMaterial({
size: mz,
color: 0xFFFFFF,
sizeAttenuation: false
});
// Particle
particles = new THREE.Points();
particles.material = material
scene.add(particles);
var getImageData = function(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, image.width, image.height);
}
var drawTheMap = function() {
let vertices = particles.geometry; // this acts as a REFERENCE!
vertices.length = 0; // clears the vertices array
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
var vertex = new THREE.Vector3();
vertex.x = x - imagedata.width / 2;
vertex.y = -y + imagedata.height / 2;
vertex.z = -Math.random()*500;
vertex.speed = Math.random() / speed + 0.015;
vertices.vertices.push(vertex);
}
}
}
particles.geometry.verticesNeedUpdate = true; // Inform three.js of the update
requestAnimationFrame(render);
};
var init = function() {
imagedata = getImageData(image);
drawTheMap();
onResize();
window.addEventListener('mousemove', onMousemove, false);
window.addEventListener('mousedown', onMousedown, false);
window.addEventListener('mouseup', onMouseup, false);
window.addEventListener('resize', onResize, false);
};
var onResize = function(){
var mov1, mov2;
ww = document.getElementById('map-container').offsetWidth;
wh = 450;
if (window.innerWidth > 850) {
mw = ww * 2;
mh = wh * 2;
mz = 6;
mov1 = 2.2;
mov2 = 1.9;
particles.material.size = mz;
} else {
mw = ww;
mh = wh;
mz = 3;
mov1 = 2;
mov2 = 2;
particles.material.size = mz;
}
renderer.setSize(mw, mh);
camera.left = ww / - mov1;
camera.right = ww / 2;
camera.top = wh / mov2;
camera.bottom = wh / - 2;
camera.updateProjectionMatrix();
};
var onMouseup = function(){
isMouseDown = false;
}
var onMousedown = function(e){
isMouseDown = true;
lastMousePos = {x:e.clientX, y:e.clientY};
};
var onMousemove = function(e){
if(isMouseDown){
camera.position.x += (e.clientX-lastMousePos.x)/100;
camera.position.y -= (e.clientY-lastMousePos.y)/100;
camera.lookAt(centerVector);
lastMousePos = {x:e.clientX, y:e.clientY};
}
};
var render = function(a) {
requestAnimationFrame(render);
particles.geometry.verticesNeedUpdate = true;
if(!isMouseDown){
camera.position.x += (0-camera.position.x)*0.06;
camera.position.y += (0-camera.position.y)*0.06;
camera.lookAt(centerVector);
}
renderer.render(scene, camera);
};
var imgData;
var image;
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
const changeState = function(state, num) {
document.getElementById('dropbox-choose').innerHTML = state;
numState = num;
switch (numState)
{
case 0:
imgData ="data:image/png;base64,iVBORw0KGgoAAA...";
break;
case 1:
imgData = "data:image/png;base64,iVBORw0KGgoAAA..."
break;
}
image.src = imgData;
}
image = document.createElement("img");
image.onload = init;
image.src = imgData;
When I click to change the image, it does not update and also I still have the problem that the website slows down. I cahaged vertcies.push to vertices.vertices.push()
I know I mentioned disposal in a previous version of my answer, but let's instead consider re-using all of your objects.
particles - Add it to the scene immediately after creation.
material - Assign it to particles immediately; No need to re-assign it every time.
geometry - Don't create it globally, we'll let it work from within particles.
Now what we're going to do is replace the vertices and tell three.js that there are new vertices to upload to the GPU.
var drawTheMap = function() {
let vertices = particles.geometry; // this acts as a REFERENCE!
vertices.length = 0; // clears the vertices array
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
var vertex = new THREE.Vector3();
vertex.x = x - imagedata.width / 2;
vertex.y = -y + imagedata.height / 2;
vertex.z = -Math.random()*500;
vertex.speed = Math.random() / speed + 0.015;
vertices.push(vertex);
}
}
}
particles.geometry.verticesNeedUpdate = true; // Inform three.js of the update
requestAnimationFrame(render);
};
The important part here (other than replacing the contents of the vertices array) is setting particles.geometry.verticesNeedUpdate = true;. This is what triggers three.js to replace the vertices on the GPU. Everything else is re-used, not recreated, so it should run fairly smooth.
The solution is change THREE.geometry to THREE.BufferGeometry
var drawTheMap = function() {
particles.geometry = new THREE.BufferGeometry();
var positions = [];
for (var y = 0, y2 = imagedata.height; y < y2; y += 2) {
for (var x = 0, x2 = imagedata.width; x < x2; x += 2) {
if (imagedata.data[(x * 4 + y * 4 * imagedata.width)] < 128) {
positions.push(x - imagedata.width / 2);
positions.push(-y + imagedata.height / 2);
positions.push(-Math.random()*500);
particles.geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
}
}
}
particles.geometry.verticesNeedUpdate = true;
requestAnimationFrame(render);
};
I'm new to THREE.js and with a very poor knowledge in physics but still I want to make a football manager game (played from top view) and I need to know that the kick of the ball is realistic as possible.
I was able to make the ball move and rotate in the correct direction while changing the position of the movement when the ball hits its boundaries.
now I need to deal with a issue of the curve of the ball and how do I make it so the ball with move in an arc to the top and to the sides (X / Y) depending of the angle of the foot hitting the ball
lets just say, I need to know how to handle two scenarios:
1) when kick start from the near bottom axis of the ball
2) when kick start from the near right axis of the ball
your help is highly appropriated. Thank you!
**
- I've added a code showing what i have so far
- I've added an image illustrating my goal (or this person scoring a goal)
/*
*
* SET UP MOTION PARAMS
*
*/
var boundries = [40, 24] //indicate where the ball needs to move in mirror position
var completeFieldDistance = boundries[0] * 2;
var fullPower = 1.8; //the power needed to move the ball the enitre field in one kick
var power = null; //will be set when the kick set in depending on the distance
var isKickStop = false; //indicate the renderer weather to stop the kick
var velocityX = null;
var velocityY = null;
//*** this is where i need help! ***
//how can I make the ball move in the Z axis with a nice curv up depending on a given angle
var curv = 15;
var peak = curv;
var velocityZ = 0;
var friction = 0.98;
var gravity = 0.5;
var bounciness = 0.8;
var minVelocity = 0.035; //for when it need to stop the kick rendering
var ballRadius = 3;
var ballCircumference = Math.PI * ballRadius * 2;
var ballVelocity = new THREE.Vector3();
var ballRotationAxis = new THREE.Vector3(0, 1, 0);
//world meshes
var ball = {};
var field = {};
/*
*
* THE KICK HANDLERS
*
*/
function onKick(angleDeg, distance) {
isKickStop = true;
peak = curv;
power = (distance / completeFieldDistance) * fullPower;
velocityX = Math.cos(angleDeg) * power;
velocityY = Math.sin(angleDeg) * power;
velocityZ = peak / (distance / 2);
requestAnimationFrame(function (params) {
isKickStop = false;
animateKick();
})
}
//** THIS IS WHERE I NEED HELP - how do I make the ball move
// render the movements of the ball
var animateKick = function (params) {
if (isKickStop) { return; }
ball.position.x += velocityX;
ball.position.z += velocityZ;
ball.position.y += velocityY;
if (Math.abs(velocityX) < minVelocity && Math.abs(velocityY) < minVelocity) {
ball.position.z = ball.bottom;
isKickStop = true;
console.log("DONE!");
return;
}
if (ball.position.z >= peak) {
ball.position.z = peak;
velocityZ *= -1;
}
if (ball.position.z < ball.bottom) {
peak *= gravity;
velocityZ *= -1;
ball.position.z = ball.bottom;
}
// Figure out the rotation based on the velocity and radius of the ball...
ballVelocity.set(velocityX, velocityY, 0);
ballRotationAxis.set(0, 0, 1).cross(ballVelocity).normalize();
var velocityMag = ballVelocity.length();
var rotationAmount = velocityMag * (Math.PI * 2) / ballCircumference;
ball.rotateOnWorldAxis(ballRotationAxis, rotationAmount);
//reduce velocity due to friction
velocityX *= friction;
velocityY *= friction;
//making sure ball is not outside of its boundries
if (Math.abs(ball.position.x) > boundries[0]) {
velocityX *= -1;
ball.position.x = (ball.position.x < 0) ? boundries[0] * -1 : boundries[0];
}
if (Math.abs(ball.position.y) > boundries[1]) {
velocityY *= -1;
ball.position.y = (ball.position.y < 0) ? boundries[1] * -1 : boundries[1];
}
}
window.onload = (function (params) {
/*
*
* SET UP THE WORLD
*
*/
//set up the ratio
var gWidth = window.innerWidth;
var gHeight = window.innerHeight;
var ratio = gWidth / gHeight;
//set the scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeaeaea);
//set the camera
var camera = new THREE.PerspectiveCamera(35, ratio, 0.1, 1000);
camera.position.z = 120;
//set the light
var light = new THREE.SpotLight(0xffffff, 1);
light.castShadow = true;
light.position.set(0, 0, 35);
scene.add(light);
// set the renderer
var renderer = new THREE.WebGLRenderer();
//properties for casting shadow
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize(gWidth, gHeight);
document.body.appendChild(renderer.domElement);
/*
*
* ADD MESH TO SCENE
*
*/
// create and add the ball
var geometry = new THREE.SphereGeometry(ballRadius, 8, 8);
//make a checkerboard texture for the ball...
var canv = document.createElement('canvas')
canv.width = canv.height = 256;
var ctx = canv.getContext('2d')
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 256, 256);
ctx.fillStyle = 'black';
for (var y = 0; y < 16; y++)
for (var x = 0; x < 16; x++)
if ((x & 1) != (y & 1)) ctx.fillRect(x * 16, y * 16, 16, 16);
var ballTex = new THREE.Texture(canv);
ballTex.needsUpdate = true;
var material = new THREE.MeshLambertMaterial({
map: ballTex
});
ball = new THREE.Mesh(geometry, material);
ball.castShadow = true;
ball.receiveShadow = false;
ball.bottom = ballRadius / 2;
scene.add(ball);
// create and add the field
var margin = 20;
var fieldRatio = 105 / 68;
var width = 90;
var height = width / fieldRatio;
var material = new THREE.MeshLambertMaterial({ color: 'green' });
var geometry = new THREE.BoxGeometry(width, height, 1);
field = new THREE.Mesh(geometry, material);
field.receiveShadow = true;
field.position.z = -1;
scene.add(field);
/*
*
* HANDLING EVENTS
*
*/
var domEvents = new THREEx.DomEvents(camera, renderer.domElement);
domEvents.addEventListener(field, 'click', function (e) {
//set points 1 and 2
var p1 = { x: e.intersect.point.x, y: e.intersect.point.y };
var p2 = { x: ball.position.x, y: ball.position.y };
var angleDeg = Math.atan2(p1.y - p2.y, p1.x - p2.x);
var a = p1.x - p2.x;
var b = p1.y - p2.y;
var distance = Math.sqrt(a * a + b * b);
window.onKick(angleDeg, distance);
}, false);
/*
*
* ANIMATION STEP
*
*/
var render = function (params) {
//render kick if it is on the go
if(!isKickStop){
animateKick();
}
//render the page
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
})()
body {
padding: 0;
margin: 0;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
<script src="https://www.klika.co.il/scripts/three.events.js"></script>
</head>
<body>
</body>
</html>
I build a model to mock this, the model accept several parameters, initial velocity and angular velocity, there are three force on the ball, gravity, air resistance force and Magnus force.
v0_x = 0; //initial velocity
v0_y = 4;
v0_z = 1;
w_x = 0 * Math.PI; // initial angular velocity
w_y = 2 * Math.PI;
w_z = 0 * Math.PI;
m = 2; //weight
rho = 1.2; // air density
g = 9.8; // gravity
f = 10; //frequency of the rotation of the ball
cl = 1.23; //horizontal tension coefficient
cd = 0.5; //air resistance coefficient
D = 0.22; // diameter of the ball
A = Math.PI * Math.pow((0.5 * D), 2); //cross-sectional area of the ball
t_step = 1 / 60;
b = (1 / 2) * cd * rho * A; //for convenience
c = cl * rho * Math.pow(D, 3) * f; // for convenience
vt_x = v0_x
vt_y = v0_y
vt_z = v0_z
animateKick = function() {
if (ball.position.y < 0) {
return;
}
tmp_1 = c * Math.pow(Math.pow(vt_x, 2) + Math.pow(vt_z, 2) + Math.pow(vt_y, 2), 2)
tmp_2 = (Math.sqrt(Math.pow(w_z * vt_y - w_y * vt_z, 2) + Math.pow(w_y * vt_x - w_x * vt_y, 2) + Math.pow(w_x * vt_z - w_z * vt_x, 2)))
tmp = tmp_1 / tmp_2
Fl_x = tmp * (w_z * vt_y - w_y * vt_z)
Fl_z = tmp * (w_y * vt_x - w_x * vt_y)
Fl_y = tmp * (w_x * vt_z - w_z * vt_y)
//Motion differential equation
a_x = -(b / m) * Math.sqrt((Math.pow(vt_z, 2) + Math.pow(vt_y, 2) + Math.pow(vt_x, 2))) * vt_x + (Fl_x / m)
a_z = -(b / m) * Math.sqrt((Math.pow(vt_z, 2) + Math.pow(vt_y, 2) + Math.pow(vt_x, 2))) * vt_z + (Fl_z / m)
a_y = -g - (b / m) * Math.sqrt((Math.pow(vt_z, 2) + Math.pow(vt_y, 2) + Math.pow(vt_x, 2))) * vt_y + (Fl_y / m)
//use formula : s_t = s_0 + v_0 * t to update the position
ball.position.x = ball.position.x + vt_x * t_step
ball.position.z = ball.position.z + vt_z * t_step
ball.position.y = ball.position.y + vt_y * t_step
//use formula : v_t = a * t to update the velocity
vt_x = vt_x + a_x * t_step
vt_z = vt_z + a_z * t_step
vt_y = vt_y + a_y * t_step
}
window.onload = (function() {
gWidth = window.innerWidth;
gHeight = window.innerHeight;
ratio = gWidth / gHeight;
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeaeaea);
camera = new THREE.PerspectiveCamera(35, ratio, 0.1, 1000);
camera.position.z = -15;
light = new THREE.SpotLight(0xffffff, 1);
light.castShadow = true;
light.position.set(0, 5, -10);
scene.add(light);
renderer = new THREE.WebGLRenderer();
//properties for casting shadow
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize(gWidth, gHeight);
document.body.appendChild(renderer.domElement);
geometry = new THREE.SphereGeometry(D, 8, 8);
//make a checkerboard texture for the ball...
canv = document.createElement('canvas')
canv.width = canv.height = 256;
ctx = canv.getContext('2d')
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 256, 256);
ctx.fillStyle = 'black';
for (y = 0; y < 16; y++)
for (x = 0; x < 16; x++)
if ((x & 1) != (y & 1)) ctx.fillRect(x * 16, y * 16, 16, 16);
ballTex = new THREE.Texture(canv);
ballTex.needsUpdate = true;
material = new THREE.MeshLambertMaterial({
map: ballTex
});
ball = new THREE.Mesh(geometry, material);
ball.castShadow = true;
ball.receiveShadow = false;
ball.bottom = D / 2;
scene.add(ball);
camera.lookAt(ball.position);
plane_geometry = new THREE.PlaneGeometry(20, 100, 32);
plane_material = new THREE.MeshBasicMaterial({
color: 'green',
side: THREE.DoubleSide
});
ground_plane = new THREE.Mesh(plane_geometry, plane_material);
ground_plane.rotation.x = 0.5 * Math.PI
ground_plane.position.y = -1
ground_plane.position.z = 20
scene.add(ground_plane);
render = function(params) {
animateKick();
renderer.render(scene, camera);
requestAnimationFrame(render);
};
render();
})
body {
padding: 0;
margin: 0;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
<script src="https://www.klika.co.il/scripts/three.events.js"></script>
</head>
<body>
</body>
</html>
This code causes a particle explosion on my page.
I attached the onClick function to a button in my HTML so it runs when I click that certain button. But when I load the HTML it automatically runs this function and after that only when I click the button.
What I need is that it wont rune when you run the HTML. The function may only run when the button is clicked.
I also would like to ask how I can change te canvas size. Since this function automatically creates a canvas where the function loads in but this one is bigger than the div with the sizes I want it to run in.
//////////////settings/////////
var movementSpeed = 30;
var totalObjects = 500;
var objectSize = 70;
var sizeRandomness = 0;
var color = 0x00BEE0;
/////////////////////////////////
var dirs = [];
var parts = [];
//var container = document.createElement('div');
//document.body.appendChild( container );
var container = document.getElementById('header');
//document.body.appendChild( header );
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000)
camera.position.z = 1000;
var scene = new THREE.Scene();
function ExplodeAnimation(x, y) {
var geometry = new THREE.Geometry();
for (i = 0; i < totalObjects; i++) {
var vertex = new THREE.Vector3();
vertex.x = x;
vertex.y = y;
vertex.z = 0;
geometry.vertices.push(vertex);
dirs.push({
x: (Math.random() * movementSpeed) - (movementSpeed / 2),
y: (Math.random() * movementSpeed) - (movementSpeed / 2),
z: (Math.random() * movementSpeed) - (movementSpeed / 2)
});
}
var material = new THREE.ParticleBasicMaterial({
size: objectSize,
color: color
});
var particles = new THREE.ParticleSystem(geometry, material);
this.object = particles;
this.status = true;
this.xDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.yDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.zDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
scene.add(this.object);
this.update = function() {
if (this.status == true) {
var pCount = totalObjects;
while (pCount--) {
var particle = this.object.geometry.vertices[pCount]
particle.y += dirs[pCount].y;
particle.x += dirs[pCount].x;
particle.z += dirs[pCount].z;
}
this.object.geometry.verticesNeedUpdate = true;
}
}
}
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.render(scene, camera);
parts.push(new ExplodeAnimation(0, 0));
render();
function render() {
requestAnimationFrame(render);
var pCount = parts.length;
while (pCount--) {
parts[pCount].update();
}
renderer.render(scene, camera);
}
window.addEventListener('mousedown', onclick, false);
window.addEventListener('resize', onWindowResize, false);
function onClick() {
event.preventDefault();
parts.push(new ExplodeAnimation((Math.random() * sizeRandomness) - (sizeRandomness / 2), (Math.random() * sizeRandomness) - (sizeRandomness / 2)));
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
As I saw you code , I think you should only put your bellow trigger code inside the click button :
renderer.render(scene, camera);
parts.push(new ExplodeAnimation(0, 0));
render();
because it's executed automatically when loading .
See My below Snippet , I ve added a sample button and run() function to show animation on click :
//////////////settings/////////
var movementSpeed = 30;
var totalObjects = 500;
var objectSize = 70;
var sizeRandomness = 0;
var color = 0x00BEE0;
/////////////////////////////////
var dirs = [];
var parts = [];
//var container = document.createElement('div');
//document.body.appendChild( container );
var container = document.getElementById('header');
//document.body.appendChild( header );
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000)
camera.position.z = 1000;
var scene = new THREE.Scene();
function ExplodeAnimation(x, y) {
var geometry = new THREE.Geometry();
for (i = 0; i < totalObjects; i++) {
var vertex = new THREE.Vector3();
vertex.x = x;
vertex.y = y;
vertex.z = 0;
geometry.vertices.push(vertex);
dirs.push({
x: (Math.random() * movementSpeed) - (movementSpeed / 2),
y: (Math.random() * movementSpeed) - (movementSpeed / 2),
z: (Math.random() * movementSpeed) - (movementSpeed / 2)
});
}
var material = new THREE.ParticleBasicMaterial({
size: objectSize,
color: color
});
var particles = new THREE.ParticleSystem(geometry, material);
this.object = particles;
this.status = true;
this.xDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.yDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
this.zDir = (Math.random() * movementSpeed) - (movementSpeed / 2);
scene.add(this.object);
this.update = function() {
if (this.status == true) {
var pCount = totalObjects;
while (pCount--) {
var particle = this.object.geometry.vertices[pCount]
particle.y += dirs[pCount].y;
particle.x += dirs[pCount].x;
particle.z += dirs[pCount].z;
}
this.object.geometry.verticesNeedUpdate = true;
}
}
}
var renderer = new THREE.WebGLRenderer();
function render() {
requestAnimationFrame(render);
var pCount = parts.length;
while (pCount--) {
parts[pCount].update();
}
renderer.render(scene, camera);
}
window.addEventListener('mousedown', onclick, false);
window.addEventListener('resize', onWindowResize, false);
function onClick() {
event.preventDefault();
parts.push(new ExplodeAnimation((Math.random() * sizeRandomness) - (sizeRandomness / 2), (Math.random() * sizeRandomness) - (sizeRandomness / 2)));
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
document.getElementById("btn").addEventListener('click',run);
function run() {
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.render(scene, camera);
parts.push(new ExplodeAnimation(0, 0));
render();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>
<button id="btn">Click to run </button>
<div id="header">
this is the code I tried below I wanted to run this animation project full screen of the window. when run the project it not run as an full screen please any one help me to run this application as full window thanks
window.onload = init();
function init() {
c = document.getElementById("canvas10");
ctx = c.getContext("2d");
ctx.fillStyle = "white";
//ctx.rect(0,0,1366,768);
// ctx.fill();
// Coordinates and speed of player
var x1 = 200 ;
var y1 = 420 ;
var SPEED = 4 ;
//tree creaion
var x3 = 600;
var y3 = 350;
//mouse1 creations
var x4 = 570;
vr y4 = 500;
var SPEED1 = 1;
//mouse2 creations
var x5 = 640;
var y5 = 560;
var SPEED2 = 1;
//mouse3 creations
var x6 = 700;
var y6 = 580;
var SPEED3 = 1;
//mouse4 creations
var x7 = 600;
var y7 = 540;
//roof creations
var x8 = 130;
var y8 = 500;
//fence creations
var x9 = 30;
var y9 = 500;
//leavies creations
var x10 = 380;
var y10 = 550;
//bee creation
var x11 = 680;
var y11 = 350;
// programming begins
// commands
stop = false;
var textImage = new Image(); // make image object
textImage.src = "text1.jpg"; // set the image path
var textImage2 = new Image(); // make image object
textImage2.src = "text2.jpg"; // set the image path
agentCanFeel = false;
agentCOLOR = "lightblue";
// Handle keyboard controls
var keyPress = {} ; // initialize the list that stores key presses
addEventListener ("keydown", function (e) {
keyPress[e.keyCode] = true; } , false);
addEventListener ("keyup", function (e) {
delete keyPress[e.keyCode]; } , false);
function Player(x1, y1) {
var playerImage = new Image(); // make image object
playerImage.src = "tom.png"; // set the image path
ctx.drawImage(playerImage, x1, y1, 80,70);
}
function Agent() {
ctx.beginPath();
ctx.arc (x2,y2, 50, 0 , 2 * Math.PI, false);
ctx.fillStyle = agentCOLOR;
ctx.fill();
var wingImage = new Image();
wingImage.src = "wings.jpg";
ctx.drawImage(wingImage, x2-40, y2-120 , 90 , 70);
}
//tree creation function
function tree()
{
ctx.beginPath();
ctx.fill();
var tree = new Image();
tree.src = "tree.png";
ctx.drawImage(tree, x3- 60, y3- 120 , 250 , 230);
}
//mouse creation function
function mouse()
{
ctx.beginPath();
ctx.fill();
var mouse = new Image();
mouse.src = "mouse.gif";
ctx.drawImage(mouse, x4- 60, y4- 120 , 40 , 30);
}
function mouse2()
{
ctx.beginPath();
ctx.fill();
var mouse1 = new Image();
mouse1.src = "mouse.gif";
ctx.drawImage(mouse1, x5- 60, y5- 120 , 40 , 30);
}
function mouse3()
{
ctx.beginPath();
ctx.fill();
var mouse2 = new Image();
mouse2.src = "mouse.gif";
ctx.drawImage(mouse2, x6- 60, y6- 120 , 40 , 30);
}
function mouse4()
{
ctx.beginPath();
ctx.fill();
var mouse4 = new Image();
mouse4.src = "mouse.gif";
ctx.drawImage(mouse4, x7- 60, y7- 120 , 40 , 30);
}
//cat roof creation function
function roof()
{
ctx.beginPath();
ctx.fill();
var roof = new Image();
roof.src = "roof.png";
ctx.drawImage(roof, x8- 60, y8- 120 , 150 , 130);
}
// fence behind cat
function fence()
{
ctx.beginPath();
ctx.fill();
var roof = new Image();
roof.src = "fence.png";
ctx.drawImage(roof, x9- 60, y9- 120 , 150 , 130);
}
// leavies creation
function leaves()
{
ctx.beginPath();
ctx.fill();
var roof = new Image();
roof.src = "leaves.png";
ctx.drawImage(roof, x10- 60, y10- 120 , 80 , 70);
}
// bee creation
function bee()
{
ctx.beginPath();
ctx.fill();
var bee = new Image();
bee.src = "bee.gif";
ctx.drawImage(bee, x11- 60, y11- 120 , 80 , 70);
}
function clear() {
ctx.rect(0,0,1000,600);
ctx.fill();
}
//mouse programming
function updatemouse()
{
x5 = x5 + SPEED1;
if (x5>650)
SPEED1 = SPEED1 * -1;
if (x5<600)
SPEED1 = SPEED1 * -1;
}
//end updateStuff
function updatemouse1()
{
x6 = x6 + SPEED2;
if (x6>800)
SPEED2 = SPEED2 * -1;
if (x6<600)
SPEED2 = SPEED2 * -1;
}
//end updateStuff
function updatemouse2()
{
x7 = x7 + SPEED3;
if (x7>800)
SPEED3 = SPEED3 * -1;
if (x7<600)
SPEED3 = SPEED3 * -1;
}
//end updateStuff
if (stopok == true)
{
ctx.drawImage(textImage, 100, 250); //STOP COMMAND
ctx.drawImage(textImage2, x5, y5-50); // OK RESPONSE
}//end if
function updateStuff() {
if (37 in keyPress && x1>0) // left arrorw
x1 = x1 - SPEED;
if (39 in keyPress && x1<1000) // right arrow
x1 = x1 + SPEED;
if (38 in keyPress && y1 > 20) // arrow up
y1 = y1 - SPEED;
if (50 in keyPress && y1 < 500) // arrow down
y1 = y1 + SPEED;
if (agentCanFeel == true ) {
agentCOLOR = "Red";
x4 = x4 + 2;
}
else
{
agentCOLOR = "Lightblue";
x4=x4 - 1;
}
} //end updateStuff
function drawStuff() {
Player(x1,y1);
// Agent();
// mouse();
mouse2();
mouse3();
mouse4();
roof();
tree();
fence();
leaves();
bee();
} //end drawStuff
function gameLoop() {
clear();
updateStuff();
drawStuff();
updatemouse();
updatemouse1();
updatemouse2();
setTimeout(gameLoop, 20); //call game loop every 20 mili sec
} //end gameloop
gameLoop();
} //end init function
I want to create an array that is having an angle of this.dAngle with the horizontal line. This is my code of the function that creates the arrow.
var offset;
if (this.dLength < 10) offset = this.dLength;
else offset = Math.min(this.dLength * 0.1, 10);
this.shape = new createjs.Shape();
//rotation
this.canvasId = this.stage.canvas.id;
this.canvas = document.getElementById(this.canvasId);
if(this.canvas) {
this.ctx = this.canvas.getContext("2d");
}
if(this.ctx) {
console.log('rotate');
this.ctx.save();
this.ctx.rotate(this.dAngle);
}
this.canvasId = this.stage.canvas.id;
this.canvas = document.getElementById(this.canvasId);
this.ctx = this.canvas.getContext("2d");
this.shape.graphics.clear();
this.shape.graphics.beginStroke("black");
this.shape.graphics.moveTo(0, 50);
this.shape.graphics.lineTo(this.dLength, 50);
this.shape.graphics.moveTo((this.dLength - offset), 50+(offset / 2));
this.shape.graphics.lineTo(this.dLength, 50);
this.shape.graphics.lineTo((this.dLength - offset), 50+(-offset / 2));
this.ctx.restore();
But the rotation is not being done. Any solutions?