[CT404]: Assignment 1 Q2 80%

This commit is contained in:
2024-10-14 22:49:12 +01:00
parent 113608f187
commit e978b3a998
10 changed files with 51481 additions and 349 deletions

View File

@ -1,200 +0,0 @@
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// draw the stick figures
draw();
function drawStickFigure(x, y) {
ctx.lineWidth = 3;
ctx.strokeStyle = 'black';
// draw the stick figure's head
ctx.beginPath();
ctx.arc(x, y - 30, 20, 0, Math.PI * 2);
ctx.stroke();
// draw the stick figure's left eye
ctx.beginPath();
ctx.arc(x - 7, y - 33, 1, 0, Math.PI * 2);
ctx.stroke();
// draw the stick figure's right eye
ctx.beginPath();
ctx.arc(x + 7, y - 33, 1, 0, Math.PI * 2);
ctx.stroke();
// draw the stick figure's mouth
ctx.beginPath();
ctx.arc(x, y - 25, 6, 0, Math.PI);
ctx.stroke();
// Body
ctx.beginPath();
ctx.moveTo(x, y - 10);
ctx.lineTo(x, y + 50); // Length of body
ctx.stroke();
// Arms
ctx.beginPath();
ctx.moveTo(x - 30, y + 10); // Left arm
ctx.lineTo(x + 30, y + 10); // Right arm
ctx.stroke();
// Legs
ctx.beginPath();
ctx.moveTo(x, y + 50); // Start at bottom of body
ctx.lineTo(x - 20, y + 100); // Left leg
ctx.moveTo(x, y + 50);
ctx.lineTo(x + 20, y + 100); // Right leg
ctx.stroke();
}
// Animation function
// function animate() {
// ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
//
// drawStickFigure(x, y); // Draw stick figure at current position
//
// // Update position
// x += dx;
// y += dy;
//
// // Check boundaries and reverse direction if necessary
// if (x + 20 > canvas.width || x - 20 < 0) dx = -dx; // Horizontal boundary check
// if (y + 100 > canvas.height || y - 50 < 0) dy = -dy; // Vertical boundary check
//
// requestAnimationFrame(animate); // Recursive call to keep animation going
// }
// Start animation
// animate();
function draw() {
// prompt the user to enter a number in a range and not continuing under a number in that range is selected
let numberStickFigures = 5;
// let numberStickFigures = 0;
// while (numberStickFigures < 1 || numberStickFigures > 5) {
// numberStickFigures = prompt("Enter an integer between 1 and 5");
// }
for (let i = 1; i <= numberStickFigures; i++) {
// place the stick figure randomly on the canvas
const x = Math.floor(Math.random() * canvas.width);
const y = Math.floor(Math.random() * canvas.height);
drawStickFigure(x, y);
}
}
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Store stick figure data
let stickFigures = [];
// Generate random number of stick figures between 1 and 5
let numberStickFigures = 5;
// Create stick figures with random positions and velocities
for (let i = 0; i < numberStickFigures; i++) {
stickFigures.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
dx: (Math.random() - 0.5) * 8,
dy: (Math.random() - 0.5) * 8,
danceSpeed: Math.random() * 5,
limbAngle: 0
});
}
// Draw the stick figure
function drawStickFigure(x, y) {
ctx.lineWidth = 3;
ctx.strokeStyle = 'black';
// Draw the stick figure's head
ctx.beginPath();
ctx.arc(x, y - 30, 20, 0, Math.PI * 2);
ctx.stroke();
// Draw the stick figure's left eye
ctx.beginPath();
ctx.arc(x - 7, y - 33, 1, 0, Math.PI * 2);
ctx.stroke();
// Draw the stick figure's right eye
ctx.beginPath();
ctx.arc(x + 7, y - 33, 1, 0, Math.PI * 2);
ctx.stroke();
// Draw the stick figure's mouth
ctx.beginPath();
ctx.arc(x, y - 25, 6, 0, Math.PI);
ctx.stroke();
// Body
ctx.beginPath();
ctx.moveTo(x, y - 10);
ctx.lineTo(x, y + 50); // Length of body
ctx.stroke();
// Arms
ctx.beginPath();
// right arm
ctx.moveTo(x, y + 10);
ctx.lineTo(x + 30, y + 10);
ctx.stroke();
// left arm
ctx.moveTo(x, y + 10);
ctx.lineTo(x - 30, y + 10);
ctx.stroke();
// Legs
ctx.beginPath();
ctx.moveTo(x, y + 50); // Start at bottom of body
ctx.lineTo(x - 20, y + 100); // Left leg
ctx.moveTo(x, y + 50);
ctx.lineTo(x + 20, y + 100); // Right leg
ctx.stroke();
}
// Update the position of each stick figure and bounce off the boundaries
function updateStickFigures() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
stickFigures.forEach((figure) => {
// Update position
figure.x += figure.dx;
figure.y += figure.dy;
// Bounce off the boundaries
if (figure.x + 20 > canvas.width || figure.x - 20 < 0) figure.dx = -figure.dx; // Horizontal boundary check
if (figure.y + 100 > canvas.height || figure.y - 50 < 0) figure.dy = -figure.dy; // Vertical boundary check
// Draw updated figure
drawStickFigure(figure.x, figure.y);
});
requestAnimationFrame(updateStickFigures); // Recursive call for animation
}
// Start animation
updateStickFigures();

View File

@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CT404: Assignment 01</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script src="script.js"></script>
</body>
</html>

View File

@ -1 +0,0 @@
console.log('Happy developing ✨')

View File

@ -1,10 +0,0 @@
{
"name": "code",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"private": true
}

View File

@ -1,125 +0,0 @@
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
// make canvas the same size as the window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// prompt user to enter a number between 1 and 5 and not continuing until one is selected
let numberStickFigures = 0;
while (numberStickFigures < 1 || numberStickFigures > 5) {
numberStickFigures = prompt("Enter an integer between 1 and 5");
}
// array to store position, speed etc of each stick figure
let stickFigures = [];
// Create stick figures with random positions and velocities
for (let i = 0; i < numberStickFigures; i++) {
stickFigures.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
dx: (Math.random() - 0.5) * 4,
dy: (Math.random() - 0.5) * 4,
angle: 0, // Initial limb angle
angleSpeed: (Math.random() * 0.05) + 0.02 // Speed of limb movement
});
}
// Draw the stick figure
function drawStickFigure(x, y, angle) {
context.lineWidth = 3;
context.strokeStyle = 'black';
// draw the head
context.beginPath();
context.arc(x, y - 30, 20, 0, Math.PI * 2);
context.stroke();
// left eye
context.beginPath();
context.arc(x - 7, y - 33, 1, 0, Math.PI * 2);
context.stroke();
context.fill(); // fill in circle
// right eye
context.beginPath();
context.arc(x + 7, y - 33, 1, 0, Math.PI * 2);
context.stroke();
context.fill();
// mouth
context.beginPath();
context.arc(x, y - 25, 6, 0, Math.PI);
context.stroke();
// torso
context.beginPath();
context.moveTo(x, y - 10);
context.lineTo(x, y + 50);
context.stroke();
// Arms with 2 parts (upper and lower arm)
const armLength = 30;
const upperArmAngle = Math.sin(angle) * Math.PI / 4; // Swinging angle for upper arms
const lowerArmAngle = Math.cos(angle) * Math.PI / -2; // Swinging angle for lower arms
context.beginPath();
// Left upper arm
context.moveTo(x, y + 10);
context.lineTo(x - armLength * Math.cos(upperArmAngle), y + 10 + armLength * Math.sin(upperArmAngle));
// Left lower arm
context.lineTo(x - armLength * Math.cos(upperArmAngle) - armLength * Math.cos(lowerArmAngle), y + 10 + armLength * Math.sin(upperArmAngle) + armLength * Math.sin(lowerArmAngle));
// Right upper arm
context.moveTo(x, y + 10);
context.lineTo(x + armLength * Math.cos(upperArmAngle), y + 10 + armLength * Math.sin(upperArmAngle));
// Right lower arm
context.lineTo(x + armLength * Math.cos(upperArmAngle) + armLength * Math.cos(lowerArmAngle), y + 10 + armLength * Math.sin(upperArmAngle) + armLength * Math.sin(lowerArmAngle));
context.stroke();
// Legs with 2 parts (thigh and calf)
const legLength = 40;
const upperLegAngle = Math.sin(angle) * Math.PI / 5; // Swinging angle for upper legs
const lowerLegAngle = Math.cos(angle) * Math.PI / 2; // Swinging angle for lower legs
context.beginPath();
// Left upper leg
context.moveTo(x, y + 50);
context.lineTo(x - legLength * Math.cos(upperLegAngle), y + 50 + legLength * Math.sin(upperLegAngle));
// Left lower leg
context.lineTo(x - legLength * Math.cos(upperLegAngle) - legLength * Math.cos(lowerLegAngle), y + 50 + legLength * Math.sin(upperLegAngle) + legLength * Math.sin(lowerLegAngle));
// Right upper leg
context.moveTo(x, y + 50);
context.lineTo(x + legLength * Math.cos(upperLegAngle), y + 50 + legLength * Math.sin(upperLegAngle));
// Right lower leg
context.lineTo(x + legLength * Math.cos(upperLegAngle) + legLength * Math.cos(lowerLegAngle), y + 50 + legLength * Math.sin(upperLegAngle) + legLength * Math.sin(lowerLegAngle));
context.stroke();
}
// Update the position and dance movements of each stick figure
function updateStickFigures() {
context.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
stickFigures.forEach((figure) => {
// Update position
figure.x += figure.dx;
figure.y += figure.dy;
// Bounce off the boundaries
if (figure.x + 20 > canvas.width || figure.x - 20 < 0) figure.dx = -figure.dx; // Horizontal boundary check
if (figure.y + 100 > canvas.height || figure.y - 50 < 0) figure.dy = -figure.dy; // Vertical boundary check
// Update limb angles for dancing
figure.angle += figure.angleSpeed;
// Draw the updated stick figure with animated limbs
drawStickFigure(figure.x, figure.y, figure.angle);
});
requestAnimationFrame(updateStickFigures); // Recursive call for animation
}
// Start animation
updateStickFigures();

View File

@ -0,0 +1,214 @@
<html>
<head>
<script src="./three.js"></script>
<script src="./OrbitControls.js"></script>
<script>
'use strict'
var raycaster, renderer, scene, camera, orbitControls, lightbulb, lampshade;
var selectedObject = null;
var selectableObjects = [];
var lastMousePos = {x: 0, y: 0};
function draw() {
// create renderer attached to HTML Canvas object
const canvas = document.getElementById("canvas");
renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
// create the scenegraph
scene = new THREE.Scene();
// create a camera
var fov = 75;
var aspect = 600 / 600;
var near = 0.1;
var far = 1000;
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(-10, 5, -2);
orbitControls = new THREE.OrbitControls(camera, canvas);
orbitControls.enableDamping = true;
orbitControls.dampingFactor = 0.25;
orbitControls.enableZoom = true;
orbitControls.autoRotate = false;
const light = new THREE.AmbientLight(0xFFFFFF);
scene.add(light);
// desk lamp base
// args: radiusTop, radiusBottom, height, radialSegments
var base = new THREE.Mesh(
new THREE.CylinderBufferGeometry(1, 1, 0.1, 12),
new THREE.MeshLambertMaterial({color: 0xff84a3}));
scene.add(base);
base.position.set(-5, -2, 0);
base.canTranslate = false; // make base unmovable
// desk lamp first arm piece
var arm = new THREE.Mesh(
new THREE.CylinderBufferGeometry(0.1, 0.1, 3, 12),
new THREE.MeshLambertMaterial({color: 0x84ffa3}));
// since we want to rotate around a point other than the arm's centre,
// we can create a pivot point as the parent of the arm, position the
// arm relative to that pivot point, and apply rotation on the pivot point
var pivot = new THREE.Object3D();
pivot.position.set(0, 0, 0); // centre of rotation we want
pivot.add(arm); // pivot is parent of arm
base.add(pivot); // base is parent of pivot
arm.canRotate = false;
// translate arm relative to pivot point
arm.position.set(0, 1.5, 0);
// rotate pivot point relative to the world
pivot.rotateOnAxis(new THREE.Vector3(0, 0, 1), -Math.PI / 6);
// second arm piece (consisting of a pivot with a cylinder as its child)
var pivot2 = pivot.clone();
pivot.add(pivot2);
// rotate the 2nd pivot relative to the 1st pivot (since it's nested)
pivot2.rotation.z = Math.PI / 3;
// translate the 2nd pivot relative to the 1st pivot
pivot2.position.set(0, 3, 0);
var arm2 = pivot2.children[0];
arm2.canRotate = false;
// args: radius, height, segments
lampshade = new THREE.Mesh(
new THREE.ConeBufferGeometry(1, 0.7, 24),
new THREE.MeshLambertMaterial({color: 0xff84a3})
);
var shadePivot = new THREE.Object3D();
pivot2.add(shadePivot); // lampshade pivot is a child of the 2nd arm pivot
shadePivot.add(lampshade);
shadePivot.position.set(0, 3, 0);
shadePivot.rotation.x = Math.PI;
selectableObjects.push(lampshade);
lampshade.canRotate = true;
lightbulb = new THREE.PointLight(0xffffff, 1, 70);
lightbulb.position.set(0, -0.7, 0);
shadePivot.add(lightbulb);
raycaster = new THREE.Raycaster();
canvas.onmousedown = handleMouseDown;
canvas.onmousemove = handleMouseMove;
canvas.onmouseup = handleMouseUp;
var box = new THREE.Mesh(new THREE.BoxGeometry(60, 5, 60), new THREE.MeshLambertMaterial({color: 0x644117}));
scene.add(box);
box.position.set(0, -5, 0);
animate();
}
function animate() {
setTimeout(animate, 1000 / 60);
orbitControls.update();
// render the scene as seen by the camera
renderer.render(scene, camera);
}
// handle mouse up events
function handleMouseUp(e) {
// reset selected object and orbit controls
selectedObject = null;
orbitControls.enabled = true;
// find the position of the click
let mouseUpX = 2 * (e.clientX - 300) / 600;
let mouseUpY = -2 * ((e.clientY - 300) / 600);
// send a raycast from the clicked position and check if it intersects with the lampshade
let lightswitchRaycaster = new THREE.Raycaster();
lightswitchRaycaster.setFromCamera({x: mouseUpX, y: mouseUpY}, camera);
let intersects = lightswitchRaycaster.intersectObject(lampshade);
// if the lampshade was clicked, toggle the lightbulb
if (intersects.length > 0) {
lightbulb.visible = !lightbulb.visible;
}
}
function handleMouseDown(e) {
// handle mouse-clicks on the canvas
// did the user click a mesh?
/* note that 0,0 is the centre of the canvas according to WebGL,
and the canvas extends from (-1,-1) to (1,1)
but 0,0 is the top-left of the canvas according to e.clientX,e.clientY,
and the canvas extends from (0,0) to (599,599)
*/
var x = 2 * (e.clientX - 300) / 600;
var y = -2 * ((e.clientY - 300) / 600);
lastMousePos.x = x;
lastMousePos.y = y;
// set up and apply the raycaster (we are returned an array of intersection objects)
raycaster.setFromCamera({x: x, y: y}, camera);
var intersects = raycaster.intersectObjects(selectableObjects);
if (intersects.length > 0) {
// disable orbit controls if an object is clicked (so it can be manipulated)
orbitControls.enabled = false;
var closestObj, closestDist;
for (var i = 0; i < intersects.length; i++) {
/*
An intersection has the following properties :
- object : intersected object (THREE.Mesh)
- distance : distance from ray start to intersection (number)
- face : intersected face (THREE.Face3)
- faceIndex : intersected face index (number)
- point : intersection point (THREE.Vector3)
- uv : intersection point in the object's UV coordinates (THREE.Vector2)
*/
if (i == 0 || intersects[i].distance < closestDist) {
closestObj = intersects[i].object;
closestDist = intersects[i].distance;
}
}
selectedObject = closestObj;
}
else
selectedObject = null;
}
function handleMouseMove(e) {
if (selectedObject != null) {
var x = 2 * (e.clientX - 300) / 600;
var y = -2 * ((e.clientY - 300) / 600);
// dx,dy is the amount the mouse just moved by in pixels
var dx = x - lastMousePos.x;
var dy = y - lastMousePos.y;
if (selectedObject.canRotate) {
// rotate the parent ('pivot') that the object is a child of
selectedObject.parent.rotation.x += dx;
selectedObject.parent.rotation.z += dy;
}
else if (selectedObject.canTranslate) {
// translate the object
selectedObject.position.x += dx * 4;
selectedObject.position.z -= dy * 4;
}
lastMousePos.x = x;
lastMousePos.y = y;
}
}
</script>
</head>
<body onload="draw();">
<!-- Note that the canvas has been positioned precisely at 0,0 so that mouse positions on the browser
are the same as mouse positions on the canvas -->
<canvas id="canvas" width="600" height="600" style="position:absolute; left:0px; top:0px"></canvas>
</body>
</html>

File diff suppressed because one or more lines are too long