Java-Gaming.org Hi !
 Featured games (84) games approved by the League of Dukes Games in Showcase (565) Games in Android Showcase (151) games submitted by our members Games in WIP (606) games currently in development
 News: Read the Java Gaming Resources, or peek at the official Java tutorials
Pages: [1] 2
 ignore  |  Print
 Utils essentials  (Read 14881 times) 0 Members and 1 Guest are viewing this topic.
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Posted 2010-03-22 14:29:30 »

I thought I'd try to get some snowball rolling here.

Rules are simple: Post a single static method "Utils" method that you find useful. Hopefully we'll have tons of methods in here that people can copy and paste to use in their own Utils classes.

These methods can be many things, but they deal with a set of parameters and return a single value.

Keep the name of the method very descriptive, not just "getBla", but "calculateBlaFromSetOfBlahblahs".

 1  2  3  4  5  6 `// Linear interpolation, get the value between a and b where t is 0-1.public static float lerp(float a, float b, float t) {   if (t < 0)      return a;   return a + t * (b - a);}`

 1  2  3  4 `// Get the euclidean distance between two points.public static float euclideanDistance(float x1, float y1, float x2, float y2) {   return (float) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));}`

Both of these can probably be optimized, so go ahead and post your optimized version.

Check out the 4K competition @ www.java4k.com
Mr. Gol

Senior Devvie

Medals: 1

 « Reply #1 - Posted 2010-03-22 18:04:02 »

In your example, for t=0 you currently do the full calculation, while you can just return "a".

I'll add a method of my own. It can be used to store application data files in the proper location for the current platform. You could use java.util.prefs, but in some cases you just want a place to store files.

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46 `/** * Returns a {@code File} that points to the application data with the  * specified path. The directory returned will be a subdirectory with * the application's name, in the platform-specific location for storing * application data. If the subdirectory does not already exist it is * created. * @param appName The name of the application. * @param path Relative path to the requested file. * @return A {@code File} object that points to the requested file. * @throws IllegalArgumentException if the path is empty or absolute. */public static File getApplicationData(String appName, String path) {    if (appName.length() == 0) {        throw new IllegalArgumentException("Invalid application name");    }            if ((path.length() == 0) || path.startsWith("/")) {        throw new IllegalArgumentException("Invalid path: " + path);    }    File appdir = null;            if (System.getProperty("os.name").startsWith("Windows")) {         appdir = new File(System.getenv("APPDATA"));    } else if (System.getProperty("os.name").startsWith("Mac OS X")) {        // This will also work for non-English versions of Mac OS X        appdir = new File(System.getenv("HOME") + "/Library/Application Support");     }        // If auto-detection failed, or if not known, fall back to user home    if ((appdir == null) || !appdir.exists() || !appdir.isDirectory()) {        appdir = new File(System.getProperty("user.home"));        appName = "." + appName;    }            File dir = new File(appdir, appName);    if (!dir.exists()) {        boolean success = dir.mkdir();        if (!success) {            throw new IllegalStateException("Cannot create directory: " + dir.getAbsolutePath());        }    }            return new File(dir.getAbsolutePath() + "/" + path);}`

Momoko_Fan

Junior Devvie

Medals: 2

 « Reply #2 - Posted 2010-03-22 19:05:42 »

If we are talking about interpolation, then I have a few as well

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22 `public static final float interpolateHermite(float v0, float v1, float v2, float v3, float v01time, float v12time, float x, float tension, float bias){       float mu2 = x * x;       float mu3 = mu2 * x;       float ts, td, a0, a1, a2, a3;              ts  = (v1 - v0) * (((1f + bias) * (1f - tension)) / 2f);       ts += (v2 - v1) * (((1f - bias) * (1f - tension)) / 2f);              td  = (v2 - v1) * (((1f + bias) * (1f - tension)) / 2f);       td += (v3 - v2) * (((1f - bias) * (1f - tension)) / 2f);       a0  =  2f * mu3 - 3f * mu2 + 1f;       a1  =       mu3 - 2f * mu2 + x;       a2  =       mu3 -      mu2;       a3  = -2f * mu3 + 3f * mu2;       return a0 * v1             + a1 * ts             + a2 * td             + a3 * v2;    }`

 1  2  3  4  5  6  7 `public static final float interpolateCatmullRom(float v0, float v1, float v2, float v3, float x){        return 0.5f * ((-v0 + 3f*v1 -3f*v2 + v3)*x*x*x                    +  (2f*v0 -5f*v1 + 4f*v2 - v3)*x*x                    +  (-v0+v2)*x                    +  2f*v1);    }`

 1  2  3  4  5  6  7  8  9  10  11 `    public static final float interpolateCubic(float v0, float v1, float v2, float v3, float x){        float p = (v3 - v2) - (v0 - v1);        float q = (v0 - v1) - p;        float r = v2 - v0;        float s = v1;        return p * x * x * x              + q * x * x              + r * x              + s;    }`

 1  2  3  4  5  6 `    public static final float interpolateCosine(float v0, float v1, float x){        float ft = x * (float)Math.PI;        float f = (1 - (float)Math.cos(ft)) * 0.5f;        return v0 * (1 - f) + v1 * f;    }`

Some noise
 1  2  3  4  5  6  7  8  9 `public static final float noise1(int x){       x = (x << 13) ^ x;       x = (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff;       return 1.0f - x / 1073741824.0f;    }    public static final float noiseSmooth1(int x){       return noise1(x) / 2.0f + noise1(x-1) / 4.0f + noise1(x+1) / 4.0f;    }`

Not sure where I got it from, but hopefully there's no copyright on functions lol
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #3 - Posted 2010-03-22 19:59:51 »

Superb! I smell a good thread coming out of this.

// This function interpolates ... by taking x1, y1, etc., and returning a processed value...

Check out the 4K competition @ www.java4k.com
pjt33

« JGO Spiffy Duke »

Medals: 39
Projects: 4
Exp: 7 years

 « Reply #4 - Posted 2010-03-22 21:20:39 »

A generic toString for debugging output with arrays:

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24 `   public static String toString(Object obj)   {      if (obj instanceof Object[])      {         StringBuilder sb = new StringBuilder();         sb.append("[");         boolean first = true;         for (Object o : (Object[])obj)         {            if (first) first = false;            else sb.append(", ");            sb.append(toString(o));         }         return sb.append("]").toString();      }      if (obj instanceof int[]) return Arrays.toString((int[])obj);      if (obj instanceof long[]) return Arrays.toString((long[])obj);      if (obj instanceof short[]) return Arrays.toString((short[])obj);      if (obj instanceof byte[]) return Arrays.toString((byte[])obj);      if (obj instanceof double[]) return Arrays.toString((double[])obj);      if (obj instanceof float[]) return Arrays.toString((float[])obj);      if (obj instanceof boolean[]) return Arrays.toString((boolean[])obj);      return obj == null ? "null" : obj.toString();   }`
pjt33

« JGO Spiffy Duke »

Medals: 39
Projects: 4
Exp: 7 years

 « Reply #5 - Posted 2010-03-22 21:23:40 »

A wrapper around Color.HSBtoRGB which works around a bug I reported 7.5 years ago.
 1  2  3  4  5  6  7 `   public static int HSBtoRGB(float hue, float saturation, float brightness)   {      // Fix for bug 4759386.      float h = (hue - (float)Math.floor(hue)) * 6f;      if (h >= 6f) hue = 0f;      return Color.HSBtoRGB(hue, saturation, brightness);   }`
pjt33

« JGO Spiffy Duke »

Medals: 39
Projects: 4
Exp: 7 years

 « Reply #6 - Posted 2010-03-22 21:29:05 »

And one more for now: a method I've found very helpful for working out why my OpenGL scene isn't rendering as I think it should:

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 `   /**    * Gets a string representing the current lighting state.    * @param gl The OpenGL handle.    * @return A string which describes the current lights at a basic level.    */   public static String lightingDebugString(GL gl)   {      // First thing to check: are we actually doing lighting at all?      boolean lighting = gl.glIsEnabled(GL.GL_LIGHTING);      if (!lighting)      {         return "Lighting is disabled; glColor controls vertex colours";      }      // Ok. We'll assemble stuff.      StringBuilder sb = new StringBuilder();      sb.append("Lighting is enabled\n");      float[] buf = new float[4];      // Global stuff. There are more parameters, but this is sufficient for      // now. Maybe this method should have a verbosity parameter?      gl.glGetFloatv(GL.GL_LIGHT_MODEL_AMBIENT, buf, 0);      sb.append("\tScene ambient light: ");      append(sb, buf);      sb.append("\n");      // How many lights must we check?      int[] ibuf = new int[1];      gl.glGetIntegerv(GL.GL_MAX_LIGHTS, ibuf, 0);      int numLights = ibuf[0];      // List info for the enabled lights.      sb.append("\tEnabled lights:\n");      int enabledLightCount = 0;      for (int i = 0; i < numLights; i++)      {         // Note that it is always the case that GL_LIGHT_i = GL_LIGHT0 + i:         // ref. http://www.opengl.org/sdk/docs/man/xhtml/glGetLight.xml         if (gl.glIsEnabled(GL.GL_LIGHT0 + i))         {            enabledLightCount++;            sb.append("\t\tLight ").append(i).append("\n");            // Key light parameters. Ignoring things like GL_SPOT_EXPONENT.            gl.glGetLightfv(GL.GL_LIGHT0 + i, GL.GL_AMBIENT, buf, 0);            sb.append("\t\t\tAmbient: ");            append(sb, buf);            sb.append("\n");            gl.glGetLightfv(GL.GL_LIGHT0 + i, GL.GL_DIFFUSE, buf, 0);            sb.append("\t\t\tDiffuse: ");            append(sb, buf);            sb.append("\n");            gl.glGetLightfv(GL.GL_LIGHT0 + i, GL.GL_POSITION, buf, 0);            sb.append("\t\t\tPosition: ");            append(sb, buf);            sb.append("\n");            sb.append("\t\t\tOther parameters snipped");         }      }      // If no lights enabled, say so.      if (enabledLightCount == 0)      {         sb.append("\t\tNone");      }      return sb.toString();   }   /**    * Utility method to append a float[] to a StringBuilder.    * @param sb The string builder to which to append.    * @param vals The array to append.    */   private static void append(StringBuilder sb, float[] vals)   {      sb.append("[");      for (int i = 0; i < vals.length; i++)      {         if (i > 0)         {            sb.append(", ");         }         sb.append(vals[i]);      }      sb.append("]");   }`
Mr. Gol

Senior Devvie

Medals: 1

 « Reply #7 - Posted 2010-03-22 22:10:32 »

A wrapper around Color.HSBtoRGB which works around a bug I reported 7.5 years ago.

Edit: Damn, the "evaluation" section isn't even filled in, which probably means that no Sun employee has ever looked into this!
i30817

Junior Devvie

 « Reply #8 - Posted 2010-03-22 22:18:16 »

 « Reply #9 - Posted 2010-03-22 22:48:29 »

It's probably already in the JRE but never find it.
 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27 `        /**    * The angle of the vector (x, y). The angle is between 0 and 2*PI.    * @param x The x value of the vector.    * @param y The y value of the vector.    * @return The angle of the vector (x, y).    */   public static double findAngle(double x, double y){      double theta = 0;      if(x == 0){         if(y>0){            theta = Math.PI/2;         }else if(y < 0){            theta = Math.PI*3/2;         }      }      if(x > 0){         theta = Math.atan(y/Math.abs(x));      }      if(x < 0){         theta = Math.PI - Math.atan(y/Math.abs(x));      }      if(theta < 0){         theta += Math.PI*2;      }      return theta;   }`

jojoh

JGO Knight

Medals: 5
Projects: 7

games4j.com

 « Reply #10 - Posted 2010-03-23 00:09:00 »

It's probably already in the JRE but never find it.

I think what you are looking for is: Math.atan2(y, x);
Except for that it is from -PI to PI IIRC.

DzzD
 « Reply #11 - Posted 2010-03-23 00:15:56 »

Not sure where I got it from, but hopefully there's no copyright on functions lol
hehe probably from hugo elias website http://freespace.virgin.net/hugo.elias/models/m_perlin.htm (NB : those lack of optimisation are hurting my eyes : /2 => * 0.5 , /constante => *1.0/constante ; unnecessary float cast )

Orangy Tang

JGO Kernel

Medals: 57
Projects: 11

 « Reply #12 - Posted 2010-03-23 01:32:33 »

Here's a nice self-contained snippet from Rebirth, to make a shallow copy from one object to an already existing one. Useful for dynamically reloading an object when it's on-disk state changes.

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56 `public static void shallowCopy(Object source, Object dest, final boolean publicOnly)   {      if (!source.getClass().isInstance(dest))         throw new IllegalArgumentException();            Field[] sourceFields = ReflectionUtil.getAllDeclaredFields(source, publicOnly);      for (int i=0; i result = new ArrayList();            Class clazz = object.getClass();      while (clazz != null)      {         Field[] fields;         if (publicOnly)            fields = clazz.getFields();         else            fields = clazz.getDeclaredFields();                  for (int i=0; i

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Riven
« League of Dukes »

« JGO Overlord »

Medals: 950
Projects: 4
Exp: 16 years

 « Reply #13 - Posted 2010-03-23 06:47:36 »

Here's a nice self-contained snippet from Rebirth, to make a shallow copy from one object to an already existing one. Useful for dynamically reloading an object when it's on-disk state changes.

 1  2  3  4  5  6  7  8  9 `...            f.setAccessible(true);   /** 'publicOnly' just gets public fields (Class.getFields vs. Class.getDeclaredFields) so we can work with reduced    *  functionality in a sandboxed environment (ie. applets)    */   public static Field[] getAllDeclaredFields(Object object, final boolean publicOnly)   {   }`

Funny thing that you are coding for unsigned applets, yet Field.setAccessible(true) will always throw a SecurityException, regardless of whether the field is 'already' public.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
Riven
« League of Dukes »

« JGO Overlord »

Medals: 950
Projects: 4
Exp: 16 years

 « Reply #14 - Posted 2010-03-23 06:50:38 »

In your example, for t=0 you currently do the full calculation, while you can just return "a".

You made him change perfectly fast lerp-code, adding a branch that will probably suck all the speed out of it.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #15 - Posted 2010-03-23 08:27:46 »

 1  2  3  4  5  6 `// Getting position in a quadratic bezier// Usage: x = quadraticBezier(x1, x2, x3, 0.5f) and y = quadraticBezier(y1,y2,y3,0.5f)// Returns the x,y point at 0.5 in the curve.public static float quadraticBezier(float a, float b, float c, float t) {   return (((1f - t) * (1f - t)) * a) + (((2f * t) * (1f - t)) * b) + ((t * t) * c);}`

Check out the 4K competition @ www.java4k.com
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #16 - Posted 2010-03-23 08:40:53 »

These are a set of rotation functions.

They essentially rotate a point around a pivot point given an angle, where angle is in degrees.

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15 `   public static float getRotatedX(float currentX, float currentY, float pivotX, float pivotY, float angle) {      float x = currentX-pivotX;      float y = currentY-pivotY;      float a = (float) Math.toRadians(angle);      float xr = (float) ((x * Math.cos(a)) - (y * Math.sin(a)));      return xr+pivotX;   }      public static float getRotatedY(float currentX, float currentY, float pivotX, float pivotY, float angle) {      float x = currentX-pivotX;      float y = currentY-pivotY;      float a = (float) Math.toRadians(angle);      float yr = (float) ((x * Math.sin(a)) + (y * Math.cos(a)));      return yr+pivotY;   }`

Check out the 4K competition @ www.java4k.com
Orangy Tang

JGO Kernel

Medals: 57
Projects: 11

 « Reply #17 - Posted 2010-03-23 10:40:04 »

Funny thing that you are coding for unsigned applets, yet Field.setAccessible(true) will always throw a SecurityException, regardless of whether the field is 'already' public.

Nope. The above code works just fine in an unsigned applet (whereas the previous version, without the 'publicOnly' would throw a security exception).

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Roquen
 « Reply #18 - Posted 2010-03-23 11:00:17 »

@Appel:

For a base version of lerp, I'd suggest skipping all range checking and allow extrapolation for t outside of [0,1]:

 1  2  3  4 `public static float lerp(float a, float b, float t) {  return a + t * (b - a);}`

For performance reasons, usage of Math.pow should be avoided when the exponent is known, esp for small exponents:

 1  2  3  4  5  6  7 `public static float euclideanDistance2D(float x1, float y1, float x2, float y2){  float dx = x1-x2;  float dy = y1-y2;   return (float)Math.sqrt(dx*dx + dy*dy);}`

It's also worth noting that distance squared is as good a metric as distance, so this can be used in many instances (esp for compares):

 1  2  3  4  5  6  7 `public static float euclideanDistanceSq2D(float x1, float y1, float x2, float y2){  float dx = x1-x2;  float dy = y1-y2;   return dx*dx + dy*dy;}`

@Momoko_Fan:

All the common Java compiler do not perform common-expression removal, so IMHO it's a good idea to manually perform.

I'd also suggest converting polynomial evaluations into Horner form:

 1  2  3  4  5  6  7  8  9 `public static final float interpolateCubic(float v0, float v1, float v2, float v3, float x){  float p = (v3 - v2) - (v0 - v1);  float q = (v0 - v1) - p;  float r = v2 - v0;  float s = v1;  return ((p*x + q)* x + r)*x + s;}`

Mr. Gol

Senior Devvie

Medals: 1

 « Reply #19 - Posted 2010-03-23 11:01:50 »

You made him change perfectly fast lerp-code, adding a branch that will probably suck all the speed out of it.

He didn't change it yet. But I assume that this means the currently existing branch for t < 0 is also slowing it down. I'm not even sure why this exists, considering the input is assumed to be between 0 and 1. If it's guarding for invalid input, why isn't there a check for inputs > 1?
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #20 - Posted 2010-03-23 11:08:34 »

No problem I know my Util methods aren't optimized, it just hasn't bothered me really. I'm already updating my class though.

Check out the 4K competition @ www.java4k.com
Roquen
 « Reply #21 - Posted 2010-03-23 11:10:45 »

Ken Perlin's 'ease' functions:

For inputs 0 <= t <= 1, returns a smooth value on [0,1].

The first version is first order continuous, the second is continous is all derv.

 1  2  3  4  5  6  7  8  9  10  11  12  13 `public static final floatperlinEase(float t){  return (t*t*(3.f-(t+t)));}public static final floatperlinEase2(float t){  float t3 = t*t*t;  return t3*(10.f+t*(-15.f+6.f*t));}`
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #22 - Posted 2010-03-23 11:23:08 »

Cubic Spline interpolation :

 1  2  3  4  5  6  7  8  9  10  11  12  13 `   // Takes in v0 and v3 points with v1 and v2 control points. t is 0-1.// Returns the interpolated at t.public static float cubicSplineInterpolate(float v0, float v1, float v2, float v3, float t) {      float A = v3 - (3f * v2) + (3f * v1) - v0;      float B = (3f * v2) - (6f * v1) + (3f * v0);      float C = (3f * v1) - (3f * v0);      float D = v0;      float v = (A * (t * t * t)) + (B * (t * t)) + (C * t) + D;      return v;   }`

Check out the 4K competition @ www.java4k.com
ryanm

Senior Devvie

Projects: 1
Exp: 15 years

Used to be bleb

 « Reply #23 - Posted 2010-03-23 12:00:47 »

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31 `/** * Calculates the mean and concentration of a number of angles *  * @param angles *           An array of angles, in radians * @return A two-element array { mean, concentration }. The *         concentration metric will be 1 if all input angles are *         identical and zero of the angles are distributed evenly *         around the circle. I doubt it varies linearly though. */public static float[] meanAngle( float[] angles ){   double meanX = 0;   double meanY = 0;   for( int i = 0; i < angles.length; i++ )   {      meanY += Math.sin( angles[ i ] );      meanX += Math.cos( angles[ i ] );   }   meanX /= angles.length;   meanY /= angles.length;   float[] results = new float[ 2 ];   results[ 0 ] = ( float ) Math.atan2( meanY, meanX );   results[ 1 ] = ( float ) Math.sqrt( meanX * meanX + meanY * meanY );   return results;}`

Too big to be a snippet, and not my code, but too nice to leave out: Riven's LUT trig methods
Riven
« League of Dukes »

« JGO Overlord »

Medals: 950
Projects: 4
Exp: 16 years

 « Reply #24 - Posted 2010-03-23 15:43:15 »

writing JPG with specified quality, to any Outputstream (not only to a file)

 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57 `   public static void writeJPG(BufferedImage img, final OutputStream out, float quality) throws IOException   {      ImageOutputStreamImpl output = new ImageOutputStreamImpl()      {         @Override         public int read(byte[] b, int off, int len) throws IOException         {            throw new UnsupportedOperationException();         }         @Override         public int read() throws IOException         {            throw new UnsupportedOperationException();         }         @Override         public void write(byte[] buf, int off, int len) throws IOException         {            out.write(buf, off, len);         }         @Override         public void write(int b) throws IOException         {            out.write(b);         }         @Override         public void flush() throws IOException         {            super.flush();            out.flush();         }         @Override         public void close() throws IOException         {            super.close();            out.close();         }      };      Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");      ImageWriter writer = iter.next();      ImageWriteParam iwp = writer.getDefaultWriteParam();      iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);      iwp.setCompressionQuality(quality);      writer.setOutput(out);      IIOImage image = new IIOImage(img, null, null);      writer.write(null, image, iwp);      writer.dispose();      output.close();   }`

Nope. The above code works just fine in an unsigned applet (whereas the previous version, without the 'publicOnly' would throw a security exception).
Sorry, was confused with field.setAccessible(true) on a publicly accessible field

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
woogley
 « Reply #25 - Posted 2010-03-23 16:14:32 »

@Riven

Didn't you create a method (for your signature trickery) that writes an Image[] to an animated GIF? Any chance that's published somewhere?
Riven
« League of Dukes »

« JGO Overlord »

Medals: 950
Projects: 4
Exp: 16 years

 « Reply #26 - Posted 2010-03-23 17:20:24 »

http://riven8192.blogspot.com/2010/02/image-java-animated-gifs.html

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings!
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #27 - Posted 2010-03-23 18:22:53 »

This is a method I just restructured. I ran a few test cases on it, and it seems to work. (No guarantees though, as I've often thought I finally cracked the solution to this but after a while it seems to fail, but pretty sure now  )

I've sometimes gone mad trying to figure out... into what direction I should interpolate a rotation, given a object facing angleFrom but needs to face a new angleTo.

Example, a defense-tower in a game that has acquired a new target and must look at it. You don't want it to rotate a 350° clockwise if it could have rotated 10° counter-clockwise!

With this method you can determine the rotation direction.

false = rotate clockwise
true = rotate counter-clockwise

 1  2  3  4 `public static boolean shouldRotateCounterClockwise(float angleFrom, float angleTo) {   float diff = (angleFrom - angleTo) % 360;   return diff > 0 ? diff < 180 : diff < -180;}`

Check out the 4K competition @ www.java4k.com
Roquen
 « Reply #28 - Posted 2010-03-23 18:35:34 »

Maybe my brain is not in gear, but doesn't the following work:

 1  2  3  4  5  6 `  float diff = (angleFrom-angleTo) % 360;  if (diff > 0) return diff<180;      return diff < -180; `
appel

JGO Wizard

Medals: 69
Projects: 4

I always win!

 « Reply #29 - Posted 2010-03-23 19:01:53 »

Maybe my brain is not in gear, but doesn't the following work:

Thanks. I've updated my function, and made my own adjustments as well

Check out the 4K competition @ www.java4k.com