NOGDUS
June 21, 2018, 12:55:25 PM *
Welcome, Guest. Please login or register.

Login with username, password and session length
 
   Home   Blogs Help Search Tags Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Sprite Motion Using Bitmasking Technique  (Read 2568 times)
0 Members and 1 Guest are viewing this topic.
Richard Marks
202192397
Administrator
Member
*

Respect: 3425
Offline Offline

Posts: 1027


happy


« on: February 07, 2012, 01:12:27 PM »

Here is a killer programming gem that I have developed myself. Cool

The purpose of this code is to ensure that your sprites move at the same speed in all 8 directions. Typically this is done by using a normalized (unit) Vector (maths. ick) and requires both a call to a square root function and two division operations.

My technique reduces the code complexity to that of a simple array look-up. No extra branching, no square root calculations, just nice fast easy code.

To my knowledge, this technique has never been done like this before, and so I hereby claim this technique as my own, and give it the official oh-so-clever name of SMUBT(pronounced as smoo bit)

Please be sure to give credit if you happen to smubt your sprites in your code.

An implementation using ActionScript 3.0
Code:
// Sprite Motion Using Bitmasking Technique
// (C) 2012, by Richard Marks 02/07/2012
// Please give credit if you use this technique in your code.
//
// movement control code reference table
//     0x00 : no motion
//     0x02 : -y motion
//     0x04 : +y motion
//     0x08 : -x motion
//     0x10 : +x motion
const mm:Array = [0, 0, 1, 3, 1, 2, 0, 0, 3, 1, 5, 5, 5, 4, 0, 0, 2, 1, 4, 5, 4, 4];
const mt:Array = [0, 0.0, 1.0, -1.0, 0.7071067811865475, -0.7071067811865475];

// set movement control code based on key input
var mcc:uint = 0x00;

if (GameController.dPadUp) { mcc |= 0x02; }
else if (GameController.dPadDown) { mcc |= 0x04; }
if (GameController.dPadLeft) { mcc |= 0x08; }
else if (GameController.dPadRight) { mcc |= 0x10; }

// look up movement value to obtain unit vector
var mx:Number = mt[mm[mcc]];
var my:Number = mt[mm[mcc + 1]];

// scale by speed for motion vector
mx *= speed;
my *= speed;

// apply motion vector to position to move sprite
sprite.x += mx;
sprite.y += my;

Logged

Tags:
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.21 | SMF © 2015, Simple Machines Valid XHTML 1.0! Valid CSS!