Code Snippets

  

Java Source Code



Movement Class

A class to help implement 360 degree movements in Video Games

Submitted By: 11ty3
Actions:
Rating:
Views: 555

Language: Java

Last Modified: September 2, 2010
Instructions: Use the hSpeed and vSpeed to move x and y coordinates in your object, works best with doubles or floats.

Snippet


  1. class Movement {
  2.     public double hSpeed, vSpeed;
  3.     public void move( double degree, double speed) {
  4.         while(degree<0) {
  5.             degree+=360;
  6.         }
  7.         while(degree>360) {
  8.             degree-=360;
  9.         }
  10.         double direction = Math.toRadians(degree);
  11.         if(direction >= 0 && direction <= 90) {
  12.             hSpeed = Math.cos(direction) * speed;
  13.             vSpeed = Math.sin(direction) * speed;
  14.         }  else if(direction >= 91 && direction <= 180) {
  15.             hSpeed = -(Math.cos(90 - direction) * speed);
  16.             vSpeed = Math.sin(90 - direction) * speed;
  17.         } else if(direction >= 181 && direction <= 270) {
  18.             hSpeed = -(Math.cos(180 - direction) * speed);
  19.             vSpeed = -(Math.sin(180 - direction) * speed);
  20.         } else if(direction >= 271 && direction <= 360) {
  21.             hSpeed = Math.cos(270 - direction) * speed;
  22.             vSpeed = -(Math.sin(270 - direction) * speed);
  23.         }
  24.     }
  25.     public double getDirection() {
  26.         double s=(vSpeed/hSpeed);
  27.         double result=(Math.atan(s));
  28.         double finalR= Math.toDegrees(result);
  29.         if(vSpeed==0 | hSpeed==0)
  30.             finalR+=180;
  31.         if(hSpeed!=0) {
  32.             return finalR;
  33.         } else if(vSpeed!=0) {
  34.             return finalR;
  35.         } else {
  36.             return 0;
  37.         }
  38.     }
  39.     public double getSpeed() {
  40.         double direction = direction();
  41.         if(direction >= 0 && direction <= 90) {
  42.             return Math.cos(direction) / hSpeed;
  43.         }  else if(direction >= 91 && direction <= 180) {
  44.             return -(Math.cos(90 - direction)) / hSpeed;
  45.         } else if(direction >= 181 && direction <= 270) {
  46.             return -(Math.cos(90 - direction)) / hSpeed;
  47.         } else if(direction >= 271 && direction <= 360) {
  48.             return Math.cos(direction) / hSpeed;
  49.         } else {
  50.             return 0;
  51.         }
  52.     }
  53. }

Copy & Paste


Comments

There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.