www.webdeveloper.com
Results 1 to 4 of 4

Thread: player movement

  1. #1
    Join Date
    Dec 2017
    Posts
    1

    player movement

    hovv do i make the player move
    Code:
    var canvas = document.querySelector("canvas"); // Creates a link to the canvas element in html
    canvas.width = 640; 	// Sets the canvas width to 640 px. Note that it's a regular property not accessing the .style
    canvas.height = 640;	// Sets the canvas height to 640 px.
    
    var surface = canvas.getContext("2d"); // Sets the context of the canvas to 2d, thus creating a surface on which to draw.
    var uInt; // Our variable for setInterval.
    var map; // The background grid.
    var islandArray = []; // Collision array for islands only.
    var scrollSpeed = 4; // A translation for all tiles.
    var images = []; // Array for image objects. 0=water, 1=island, 2=gap
    var imgStr = ["water", "island", "gap", "sonic"]; // Ship added.
    const ROWS = 10;
    const COLS = 11;
    
    var islandChance = 33;  // Percentage to spawn island tile.
    var gapMoveChance = 66; // Percentage to move the gap tile.
    var gapRow = Math.floor(Math.random() * ROWS); // 0-9.
    
    var player = {img:null, x:128, y:320}; // Player object.
    var playerSprite = 0; 		// Index of the sprite to display. 0-3.
    var maxSprites = 4;  		// Number of sprites in sheet.
    var spriteCtr = 0; 			// Counter for changing sprite.
    var framesPerSprite = 6;	// Number of frames per single sprite.
    
    createMap(); // Our initial function call to generate map.
    
    function update() // One run of this update function represents a single 'frame'
    {
    	// Get Player Input
    	// Move Player
    	animatePlayer();
    	scrollMap();
    	checkCollision();
    	render(); 
    }
    
    function createMap()
    {
    	for (var i = 0; i < imgStr.length; i++)
    	{
    		images[i] = new Image();
    		images[i].src = "../img/"+imgStr[i]+".png";
    	}
    	map = []; // Create map array first dimension.
    	for (var row = 0; row < ROWS; row++)
    	{
    		map[row] = []; // For each row, create 2nd dimension for columns.
    		for (var col = 0; col < COLS; col++)
    		{
    			var tile = {}; 	  // Create empty object.
    			tile.x = col*64;  // Add custom x property.
    			tile.y = row*64;  // Add custom y property.
    			tile.img = images[0]; // Link tile to water image.
    			map[row][col] = tile; // Tile object is stored in 2D array.
    		}
    	}
    	player.img = images[3];
    	uInt = setInterval(update, 33.34); // Start off at 30 frames per second.
    }
    
    function animatePlayer()
    {
    	spriteCtr++; // frame counter.
    	if (spriteCtr == framesPerSprite)
    	{
    		spriteCtr = 0;
    		playerSprite++;
    		if (playerSprite == maxSprites)
    			playerSprite = 0;
    	}
    }
    function scrollMap()
    {
    	// Iterate through all the tiles in map.
    	for (var row = 0; row < ROWS; row++)
    	{
    		for (var col = 0; col < COLS; col++)
    		{
    			map[row][col].x -= scrollSpeed; // Subtract speed from tile's x.
    		}
    	}
    	if (map[0][0].x <= -64) // If first column goes fully off canvas.
    	{
    		for (var row = 0; row < ROWS; row++) // For each row.
    		{
    			// Remove tile from islandArray?
    			if (islandArray.indexOf(map[row][0]) == 0)
    				islandArray.shift(); // Removes first element.
    			console.log(islandArray.length); // Prove that it works.
    			map[row].shift(); // Remove first element in that row.
    			var tile = {}; // Create new tile.
    			tile.x = (COLS-1)*64;
    			tile.y = row*64;
    			setTileType(tile, row);	// Tile is passed by reference so we can change it in function.	
    			map[row].push(tile); // Add new tile to end of row.
    		}
    		//Moving the gap.
    		var randRoll = Math.ceil(Math.random() * 99);
    		if (randRoll <= gapMoveChance)
    		{
    			if (gapRow == 0)
    				gapRow++;
    			else if (gapRow == ROWS-1)
    				gapRow--;
    			else
    				gapRow += (1 - (Math.floor(Math.random() * 2) * 2)); // 1 or -1
    		}
    	}
    }
    
    function setTileType(t, r) // T holds tile and r holds row.
    {
    	
    	if (r == gapRow)
    		t.img = images[0];
    	else
    	{
    		var randRoll = Math.ceil(Math.random() * 99); // Roll the dice. 1-100.
    		if (randRoll <= islandChance)
    		{
    			t.img = images[1];
    			islandArray.push(t);
    		}
    		else
    			t.img = images[0];
    	}
    }
    
    function checkCollision()
    {
    	for (var i = 0; i < islandArray.length; i++)
    	{
    		if (!(player.x+12 > islandArray[i].x+52 ||	// player left > island right
    			  player.x+52 < islandArray[i].x+12 ||	// player right < island left
    			  player.y+32 > islandArray[i].y+52 ||	// player top > island bottom
    			  player.y+48 < islandArray[i].y+40 ))	// player bottom < island top
    		{
    			window.alert("Sonic is dead");
    			clearInterval(uInt); // Stop update, also the render.
    		}
    	}
    }
    
    function render()
    {
    	surface.clearRect(0,0,canvas.width,canvas.height); // Clears what was drawn on the canvas within the specified rectangle.
    	// Render the tiles.
    	for (var row = 0; row < ROWS; row++)
    	{
    		for (var col = 0; col < COLS; col++)
    		{
    			surface.drawImage(map[row][col].img, map[row][col].x, map[row][col].y);
    		}
    	}
    	// Render the player.
    	surface.drawImage(player.img,
    					  64*playerSprite, 0, 64, 64, 	// Source rectangle.
    					  player.x, player.y, 64, 64);  // Position and size on canvas.
    }

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,765
    30 fps! IMHO You're using the wrong language, maybe you need a compiled language to render your game..

    So can you please indicate the line what the browser is saying has the error please?
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,765
    This may be some useful information, I dug it up after a google search for frame rate for HTML5 canvas, the problem will be as I suspected, down to the ability of the PC, so on older PC's that just fast enough to run windows or linux and HTML5, may choke on your game, so the frame rate will need to be calculated.

    https://www.viget.com/articles/time-based-animation
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  4. #4
    Join Date
    Dec 2012
    Posts
    1,609
    How do you intend to move the player? I guess by pressing the arrow keys?
    Please attach your images.
    Remark: Using requestAnimationFrame is recommended for animations:
    https://developer.mozilla.org/de/doc...AnimationFrame
    Last edited by Sempervivum; 12-22-2017 at 07:40 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.33859 seconds
  • Memory Usage 2,876KB
  • Queries Executed 14 (?)
More Information
Template Usage (33):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (1)bbcode_code
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (4)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (4)postbit
  • (4)postbit_onlinestatus
  • (4)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates