# Question
Title: How do I calculate paths for objects with limited acceleration?
For example, say I have a car and a car has a specific minimum turning radius and I want to drive that car from point a to point b, but the car isn't facing point b. How do I compute a path to point b? Being able to specify the orientation at the point b would also be good (say you want to drive to your driveway and then pull in to your garage -- it doesn't do much good if you got to your driveway by driving over your lawn and are facing sideways :)

A pointer to documentation (or even just a name) would be perfectly fine -- I'm having trouble finding anything at all.

In my attempts, they work in simple cases, but fail miserably in situations such as when point b is closer to a than the minimum turning radius.

For example, how would you determine a path similar to this (the bold path):

edit: In my actual problem, there are some simple pathing constraints, but I already have an A\* algorithm in place that works, but it allows things to make instantaneous heading changes, so it looks silly seeing a car suddenly make a 90˚ turn on a dime when they get to a turn point.

# Answer
I haven't worked through the full equations for this yet, but here's some visuals to help wrap our heads around the problem. It boils down to some geometry:

(Car icons via Kenney)

From any given starting point and orientation, we can draw two circles with our minimum turning radius - one on the left, one on the right. These describe the points on the tightest possible start to our path.

We can do the same for any desired end position and orientation. These circles describe the tightest possible end to our path.

Now the problem reduces to finding a path that joins one of the start circles to one of the end circles, kissing each one along its tangent.

(This is assuming we don't need to pathfind around obstacles in-between, which wasn't mentioned in the question. Stormwind's answer gets into how we can use navigation graph information for these types of problems. Once we have the sequence of nodes to pass through, we can apply the method below to each segment of the plan.)

If, for simplicity, we use straight lines, we get something like this:

This gives us the limiting case. Once you've found a path by this method, you can artificially inflate one or both start & end circles to get a less direct but smoother path, up until the point where the two circles kiss.

## Computing these paths

Let's work out the cases for one turning direction - say we begin our path by turning right.

The center of our right turning circle is:

`startRightCenter = carStart.position + carStart.right * minRadius`

Let's call the angle of the straight section of our path (measured from the positive x-axis) `pathAngle`

If we draw a vector from `rightCenter` to the point where we leave the turning circle (at which point we must be facing pathAngle), then that vector is...

`startOffset = minRadius * (-cos(pathAngle), sin(pathAngle))`

That means the point where we leave the circle must be...

`departure = startRightCenter + startOffset`

The point where we re-enter a turning circle depends on whether we're aiming to end with a left or a right turn:

```
// To end with a right turn:
reentry = endRightCenter + startOffset

// To end with a left turn: (crossover)
reentry = endLeftCenter - startOffset

```

Now, if we've done our job right, the line joining `departure` to `reentry` ought to be perpendicular to `startOffset`:

```
dot(reentry - departure,  startOffset) = 0

```

And solving this equation will give us the angle(s) at which this is true. (I use a plural here because technically there are two such angles, but one of them involves driving in reverse which is usually not what we want)

Let's substitute the right turn to right turn case as an example:

```
dot(endRightCenter + startOffset - startRightCenter - startOffset, startOffset) = 0
dot(endRightCenter - startRightCenter, startOffset) = 0
pathAngle = atan2(endRightCenter - startRightCenter)

```

The crossover case is more complicated - it's the one I haven't worked out all the math for yet. I'll post the answer without for now, in case it's useful to you while I work out the remaining details.

## Edit: Destination inside minimum turning radius

It turns out, this method often works out-of-the box even when the destination is closer than our minimum turning distance. At least some part of one of the re-entry circles ends up outside the turn radius, letting us find a viable path as long as we don't mind it getting a bit pretzel-like...

If we don't like the path we get that way (or if one isn't feasible - I haven't checked every case exhaustively - maybe there are impossible ones), we can always drive straight forward or back until we get a suitable kissing contact between a start & end circle, as diagrammed above.
> 11 votes

# Answer
This very much depends on the rest of your data model for the navigation. Ie. what data you have handy, what you can easily add data and how you consume it.

Taking a similar scenario from a traffic system at water, and with the assumtion that

* you are in a game loop
* you have a node path system
* your cars behave like an autonomous objects that control themselves "from inside", using own force and steering
* your cars do not move like on rails

you could have something like below (forgive me for the childish appearance of the pictures)

(The red squares are the nodes, red lines are node interconnections. Assume you used a pathfinding solver that gave nodes 1-9 to drive through; nodes 4-9 seen on the picture and you want to go through nodes indicated by the green line, to the garage at node #9; however you do not want to go precisely at the green line, instead stay naturally at the right side lane and do smooth manouvers).

Each node would have **metadata** which holds for example a radius, or multiple ones, for various purposes. One of them is the blue circle, which provides **aiming guidance for the cars**.

At **any occasion**, the vehicle needs to **be aware of the next two node points** P(next) and P(next+1), and their positions. Naturally, the car has a position as well. A car aims at the **right side tangent** of the blue metadata-circle of P(next). So do cars going in opposite direction, hence they won't collide. Aiming at the tangent means the car can approach the circle from any direction, and always keep right. This is a rough basic principle, that can be improved in many ways.

P(next+1) is needed to determine a distance - as the car reaches P(next), or gets inside some radius of it's metadata, it can adjust it's steering angle depending on **how far away** P(next+1) is. Ie. if it's close, turn much, if it's far away, turn little. Apparently there needs to be other rules & edge conditions as well, for example calculation of a distance between the car and a help line based on the right side tangents of P(next) and P(next+1), and a correction by that - a will to stay on the dashed (above pic) and dotted (below pic) line.

In any case, as the car **passes one node**, it **forgets it and begins to look at the next two ones**.

To your question. Apparently, when reaching node 7 (in the pic above, seen as node 2 in the picture below), it **cannot turn enough**.

One possible solution it to **construct some help lines** and **maintain a goal all time**, and then have the car move by it's own physics settings (accelerate at a specified rate, reverse slower, take node metadata speedlimits into account, brakes at a given or calculated G, etc.). As said, the car is an autonomous, self-describing, self-carrying object in this scenario.

Have the green **help lines 1,2,3**. As the car reaches the **magenta circle**, it begins it's turn to right. At this point, you can already calculate that it won't succeed (you know the max turn rate and can calculate the curve, and can see that it will cross both helplines 2 and 3). Turn steering full right and let it drive ahead (by physics increments) and slow it down as it reaches help line 3 (gets close to - use thresholds, f(dist to helpline) etc). When it is **at** help line 3, go into **reverse** mode, turn the steering to **full opposite**. Let it reverse until the it **reaches help line 4** (the connection line between node 1 and 2 - google for "point at side of line algorithm"). Slow down, as it reaches it, go into **drive ahead** mode again, turn the wheel. Repeat until the road is clear - apparently it was sufficient with 1 extra manouver this time.

This is the general idea: During the game loop, or when checking the games task que system:

* Check car position, speed, angle etc. against the **current edge limits & goal**,
* If **not reached yet**, **continue with what you were doing** (let physics move it; the car has an rpm and a gear). Insert a new check in your que system, to happen in for example 0.1 s.
* If **reached**, calqculate **new conditions, set the data and begin**. Insert a new check to happen in the que system in for example 0.1 s.
* Complete the loop cycle - continue, repeat.

By giving the nodes and the cars suffucient data, there will be movement and continuation.

Edit: And adding: This naturally needs fine tuning. Your simulation behavious may require different help lines, metadata, circles, anything. This would give an idea of one possible solution though.
> 1 votes

# Answer
I ended up doing what DMGregory suggested and it works well. Here's some relevant code (though not standalone) that can be used for computing the two styles of tangents. I'm sure this code isn't efficient, and it's probably not even correct in all situations, but it's working for me so far:

```
bool Circle::outer_tangent_to(const Circle & c2, LineSegment & shared_tangent) const {
    if (this->direction != c2.direction) {
        return false;
    }
    if (this->radius != c2.radius) {
        // how to add it: http://mathworld.wolfram.com/Circle-CircleTangents.html
        // just subtract smaller circle radius from larger circle radius and find path to center
        //  then add back in the rest of the larger circle radius
        throw ApbException("circles with different length radius not supported");
    }

    auto vector_to_c2 = c2.center - this->center;
    glm::vec2 normal_to_c2;
    if (this->direction == Circle::CW) {
        normal_to_c2 = glm::normalize(glm::vec2(-vector_to_c2.y, vector_to_c2.x));
    } else {
        normal_to_c2 = glm::normalize(glm::vec2(vector_to_c2.y, -vector_to_c2.x));
    }

    shared_tangent = LineSegment(this->center + (normal_to_c2 * this->radius),
                                 c2.center + (normal_to_c2 * this->radius));
    return true;
}

bool Circle::inner_tangent_to(const Circle & c2, LineSegment & tangent) const {

    if (this->radius != c2.radius) {
        // http://mathworld.wolfram.com/Circle-CircleTangents.html
        // adding this is non-trivial
        throw ApbException("inner_tangents doesn't support circles with different radiuses");
    }

    if (this->direction == c2.direction) {
        // inner tangents require opposing direction circles
        return false;
    }

    auto vector_to_c2 = c2.center - this->center;
    auto distance_between_circles = glm::length(vector_to_c2);

    if ( distance_between_circles < 2 * this->radius) {
//      throw ApbException("Circles are too close and don't have inner tangents");
        return false;
    } else {
        auto normalized_to_c2 = glm::normalize(vector_to_c2);
        auto distance_to_midpoint = glm::length(vector_to_c2) / 2;
        auto midpoint = this->center + (vector_to_c2 / 2.0f);

        // if hypotenuse is oo then cos_angle = 0 and angle = 90˚
        // if hypotenuse is radius then cos_angle = r/r = 1 and angle = 0
        auto cos_angle = radius / distance_to_midpoint;
        auto angle = acosf(cos_angle);

        // now find the angle between the circles
        auto midpoint_angle = glm::orientedAngle(glm::vec2(1, 0), normalized_to_c2);

        glm::vec2 p1;
        if (this->direction == Circle::CW) {
            p1 = this->center + (glm::vec2{cos(midpoint_angle + angle), sin(midpoint_angle + angle)} * this->radius);
        } else {
            p1 = this->center + (glm::vec2{cos(midpoint_angle - angle), sin(midpoint_angle - angle)} * this->radius);
        }

        auto tangent_to_midpoint = midpoint - p1;
        auto p2 = p1 + (2.0f * tangent_to_midpoint);
        tangent = {p1, p2};

        return true;
    }
};

```

Here are two movies of the code above in action:

Here's an "outer" path: http://youtube.com/watch?v=99e5Wm8OKb0 and here's a "crossing" path: http://youtube.com/watch?v=iEMt8mBheZU

If this code helps but you have questions about some of the parts that aren't shown here, just post a comment and I should see it in a day or two.
> 0 votes

---
Tags: algorithm, ai, path-finding
---


# Question
Title: HLSL texture not reading from register S1
I made a simple post processing shader, that draws scanlines. This all works perfectly. I wanted to make it a bit more interesting by applying a shadowmask instead so I wanted to pass a texture to the shader. From my understanding the Spritebatch sets Texture Register(S0), so I set my shadowmask texture to Texture Register(s1).

When applying the shader is seems that both S0 *and* S1 contain the texture I plan to draw. I have tried to set parameters in different ways- without succes. How can I pass the Texture?

My HLSL code:

```
sampler ScreenTextureSampler: register (s0); // This is the texture that SpriteBatch will try to set before drawing
sampler ShadowSampler: register (s1); // This is set in GraphicsDevice.Textures[1];

int colorlines = 2;
int shadowlines = 1;

//------------------------ PIXEL SHADER ----------------------------------------

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
    float4 color = tex2D(ScreenTextureSampler, texCoord.xy);
    float4 maskcolor = tex2D(ShadowSampler, texCoord.xy);

    float ypos = pos.y;
    float scanline = (ypos) % (colorlines + shadowlines);
    float intensity = scanline < colorlines ? 1 : 0.20f;

    //comment out one of these two return statements...
    return maskcolor*intensity; //note this return has the exact same result
    return color*intensity;     //as this one! even though the samplers point at different registers.

}

technique Postprocessing
{
    pass Pass1
    {
        PixelShader = compile ps_4_0  PixelShaderFunction();
    }
}

```

This shader is loaded in an `Effect` called `Assets.GameArt.PostProcessor`. I have a shadowmask `Texture2D` in `Assets.GameArt.shadowTexture`.

My C#, Monogame code looks like this:

```
        gd.SetRenderTarget(null);

        sb.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone, Assets.GameArt.PostProcessor, Resolution.getTransformationMatrix());

        gd.Textures[1] = Assets.GameArt.shadowTexture;

        sb.Draw(_gameRenderTarget, Vector2.Zero, _camera.Viewport, Color.White);

        sb.End();

```

`gd` points to the `GraphicsDevice` and `sb`is the `spriteBatch`. I first render my scene to a `_gameRenderTarget`.

Why isn't the Texture passed via the S1 register (or: why do the texture samplers both return the same result?)

# Answer
It turns out that this is due to optimisation of the .fx compiler. When only one sampler is actually **used** (regardless of the number of samplers being declared) the effect is compiled to be optimized to only read from the first register.

So: With this declaration:

```
sampler ScreenTextureSampler: register (s0) // This is the texture that SpriteBatch will try to set before drawing
{
    Texture = (Diffuse);
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = wrap;
    AddressV = wrap;
};

Texture2D Shadow;
sampler ShadowSampler: register (s1)
{
    Texture = (Shadow);
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = wrap;
    AddressV = wrap;
};

```

The results depend on what is done with the values. So this code:

```
float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
    float4 color = tex2D(ScreenTextureSampler, texCoord.xy);
    float4 maskcolor = Shadow.Sample(ShadowSampler, texCoord.xy);

    return maskcolor;
}

```

Doesn't use the `color` variable and therefore also not two samplers. This causes the `maskcolor` to get optimized and read from the *first* register (s0) instead.

```
float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
    float4 color = tex2D(ScreenTextureSampler, texCoord.xy);
    float4 maskcolor = Shadow.Sample(ShadowSampler, texCoord.xy);

    return color * maskcolor;
}

```

Uses both of the samplers and yields the correct result.

**Conclusion:** The effect compiler optimizes and discards any values that do not contribute to the return value. The samplers do not read from `fixed` registers, but are used in the order they are used in the pixel shader (so the first call to a sampler reads from the s0, the second call reads from s1 and so on).
> 2 votes

# Answer
You were adding **Assets.GameArt.shadowTexture** as Texture2D to your graphicdevice but there are no any texture associated in your HLSL file. You need add Texture2D to your pixel shader file and use your sampler to sample your texture2D. I suggest to render it without spritebatch and go one level lower and create your own quad with vertices, then render it with a pixel shader like as following:

```
Texture2D Texture : register(t0);
SamplerState Sampler : register(s0);

float4 main(PS_In IN) : SV_TARGET
{
    return Texture.Sample(Sampler, IN.uv);
}

```
> 0 votes

---
Tags: xna, shaders, monogame, hlsl
---


# Question
Title: Ease out elastic function with equivalent start and end values?
I have an elastic ease out function, formula in code:

```
float easeOutElastic(float t, float b, float c, float d) {
    float ts = (t/=d) * t;
    float tc = ts*t;
    return b+c*(33*tc*ts + -106*ts*ts + 126*tc + -67*ts + 15*t);
}

```

Taken from here, the elastic out small variant: http://www.timotheegroleau.com/Flash/experiments/easing\_function\_generator.htm

I'm trying to modify the function so that the start and end values are equivalent. Essentially the red line.

I am not sure which of the parameters to modify to achieve this. Is anyone familiar with this particular easing function that could provide some guidance?

My goal is to use this function on the scaleY param of a rectangle I'm animating. I think this would provide a nice stretch/squash animation, where the rectangle returns to its original size at the end of the animation.

Thank you

# Answer
> 1 votes
You can do following (in pseudocode):

```
if (x < threshold)
    return std::max(1, easeOutElastic(...));
else
    return easeOutElastic(...);

```

In this code, `threshold` means any value between X positions of two first intersections of `Y=1` and `easeOutElastic(...)`. (Thus, the minimal value is equal to length of the red line.)

---
Tags: mathematics, animation
---


# Question
Title: How can I use web browser controls for non-browser game GUI?
I'm looking for a way to get a modern browser's level of customization and rendering quality in my c# monogame to avoid using roundabout/limited/buggy GUI toolkits and to get better fonts without having to use pre-generated bitmap spritesheets (unicode support).

Is there a way to, for example, render a behind-the-scenes browser page instance onto a texture and overlay it above everything to act as GUI, along with all or just basic events (click, key press, hover, drag'n'drop)?

I've already tried using WinForms, but it's slow and most importantly, doesn't offer easy addition of custom controls which I'd very much like to use in my game. Otherwise I'd have to reimplement the whole thing in c#, but I'd rather not reinvent any wheels. For example, long lists, spreadsheets, flow controls with titles and descriptions for every item is a typical job for css, but not for WinForms.

And for the font part I'd like to get all the effects, which WinForms doesn't provide, and using the xna content pipeline, they have to be pre-baked in the bitmap font, which makes it insane to try to do dynamic font effects.

I understand that such great functionality might come at a great processing cost, but I think it's really gonna be worth the precision and font quality.

# Answer
Have you considered trying to implement WPF instead of Winforms?

I've not personally attempted to get either Monogame or XNA working with WPF, but it does seem to be doable: https://blogs.msdn.microsoft.com/nicgrave/2010/07/25/rendering-with-xna-framework-4-0-inside-of-a-wpf-application/

WPF is a good deal better than Winforms in a lot of cases, especially when trying to add custom controls.
> 0 votes

---
Tags: c#, xna, monogame, gui, css
---


# Question
Title: How do you create a camera with target-focus behavior in Java?
After making some progress in my game, I was looking around for camera scrolling methods to use for my TDS game and found one that I thought would work well for it.

This is an example of what sort of scrolling I want:

The creator of the document called it a target-focus camera (I do not know if there is an official name for it), and I was wondering how to create camera scrolling like that featured in the example and if anyone has examples that I can look at to see how it works and such.

Please note that there are quite a few things in here that will be removed due to not being needed. Most of them are the "is never used" stuff.

Player class.

```
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import java.io.*;
    import java.awt.event.MouseEvent;
    import java.lang.Math;

   public class Player
    {
    // prototype of the mouse location information.
     PointerInfo a = MouseInfo.getPointerInfo();
     Point b = a.getLocation();
     int mX = (int)b.getX();
     int mY = (int)b.getY();

     private int xPos, yPos, r;
     int dist = 1;
     //information on what part of the world the player is at.
     private int secX,secY;

private int dx,dy;
//speed will depend on what ship Player is using and what items it has.
private int speed;
//   private int xLoc, yLoc;
//  private Sector location;

//prototype variables to dictate where the camera will center
int cX = (mX - xPos) * dist + xPos;
int cY = (mY - yPos) * dist + yPos;

private String userName;

 private Ship ship;
// private Weapon weapon;
// private Engine engine;
private boolean left;
private boolean right;
private boolean up;
private boolean down;
//  private boolean firing;

private Color color1;
private Color color2;
// Variable to use when finding the angle needed to turn.
private double angleToTurn;
double mx, my;

public Player(Ship s){
 setShip(s);
 //  x = GameData.WIDTH / 2;
  //  y = GameData.HEIGHT / 2;
 xPos = s.getX();
 yPos = s.getY();
 r = s.getR();

    dx = 0;
    dy = 0;
    speed = 5;

    color1 = Color.WHITE;
    color2 = Color.RED;

  //  firing = false;
  //  firingTimer = System.nanoTime();
  //  firingDelay = 200;

  //   recovering = false;
  //  recoveryTimer = 0;

 //   score = 0;
    }

public void setShip(Ship s){
ship = s;
}

//  public int getXLoc(){return xLoc;}
 //   public int getYLoc(){return yLoc;}
 //   public Sector getLocation(){return location;}
public int getx() { return xPos; }
public int gety() {return yPos;}
public int getr() { return r; }

 public void setLeft(boolean b) { left = b; }
 public void setRight(boolean b) { right = b; }
 public void setUp(boolean b) { up = b; }
 public void setDown(boolean b) { down = b; }

 //TODO Add controls for mouse based on what class of ship it is.
  public void update() {

    if(left) {
        dx = -speed;
    }
    if(right) {
        dx = speed;
    }
    if(up) {
        dy = -speed;
    }
    if(down) {
        dy = speed;
    }

    xPos += dx;
    yPos += dy;

    if(xPos < ship.getX2() ){

      xPos = ship.getX2();
   }
    if(yPos    < ship.getY2()  ){
      yPos = ship.getY2();

    }

    if(xPos > GameData.WIDTH - r){xPos = GameData.WIDTH - r;
     }
    if(yPos > GameData.HEIGHT - r){
    yPos = GameData.HEIGHT - r;

    }

    dx = 0;
    dy = 0;

    // firing
    /*
     if(firing){long elapsed = (System.nanoTime() - firingTimer) / 1000000;
        GamePanel.bullets.add(new Bullet(270, x, y));
     if(elapsed > firingDelay) {

        firingTimer = System.nanoTime();

        }

    }
   */

    /*
    if(recovering) {
        long elapsed = (System.nanoTime() - recoveryTimer) / 1000000;
        if(elapsed > 2000) {
            recovering = false;
            recoveryTimer = 0;
        }
    }
    */

}

 public void draw(Graphics2D g) {

    g.drawImage(ship.buff, xPos, yPos, null);

    /*
         g.setColor(color1);
        g.fillOval(x - r, y - r, 2 * r, 2 * r);

        g.setStroke(new BasicStroke(3));
        g.setColor(color1.darker());
        g.drawOval(x - r, y - r, 2 * r, 2 * r);
        g.setStroke(new BasicStroke(1));
    */

}

public void moveToNextLoc(Sector m){}

//TODO add mouse rotation to the player (to start out with)
}

```

GameData

```
import javax.swing.JPanel;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;
//import javax.swing.*;
//import javax.imageio.*;
//import java.io.*;

import java.awt.event.MouseEvent;
//import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class GameData extends JPanel implements Runnable, KeyListener, MouseMotionListener
{
// instance variables - replace the example below with your own
  //   MouseListener mouse = new MouseMotionListener();
  Point playerPoint;
  Point turretPoint;

public static int WIDTH = 400;
public static int HEIGHT = 400; // stuff here may change
public static int MINWIDTH = 0;
public static int MINHEIGHT = 0;
private int FPS = 30;
// private double averageFPS;
private Thread thread;
private boolean running;

private BufferedImage image;
private Graphics2D g;

public static Player userPlayer;
public static ArrayList<Bullet> bullets;
public static ArrayList<Text> texts;

 //  float angle = (float)(Math.atan2(userPlayer.gety() - mouse.y, userPlayer.getx() - mouse.x));
 public GameData() {
 super();
 setPreferredSize(new Dimension(WIDTH, HEIGHT));
 setFocusable(true);
 requestFocus();

 }

public void addNotify() {
super.addNotify();
if(thread == null) {
thread = new Thread(this);
thread.start();
}
addKeyListener(this);
}

public void run() {

this.requestFocus();
running = true;

image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
g.setRenderingHint(
 RenderingHints.KEY_ANTIALIASING,
 RenderingHints.VALUE_ANTIALIAS_ON);
 g.setRenderingHint(
 RenderingHints.KEY_TEXT_ANTIALIASING,
 RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

userPlayer = new Player(sampleShip);
//bullets = new ArrayList<Projectile>();
//enemies = new ArrayList<Enemy>();
//powerups = new ArrayList<PowerUp>();
//explosions = new ArrayList<Explosion>();
texts = new ArrayList<Text>();

long startTime;
long URDTimeMillis;
long waitTime;
long totalTime = 0;

int frameCount = 0;
int maxFrameCount = 30;

long targetTime = 1000 / FPS;

//hue = 0;

// GAME LOOP
while(running) {

startTime = System.nanoTime();

gameUpdate();
gameRender();
gameDraw();

URDTimeMillis = (System.nanoTime() - startTime) / 1000000;

waitTime = targetTime - URDTimeMillis;

try {
Thread.sleep(waitTime);
}
catch(Exception e) {
}

frameCount++;
if(frameCount == maxFrameCount) {
//   averageFPS = 1000.0 / ((totalTime / frameCount) / 1000000);
 frameCount = 0;
totalTime = 0;
}

}

g.setColor(new Color(0, 100, 255));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.WHITE);
g.setFont(new Font("Century Gothic", Font.PLAIN, 16));
String s = "G A M E   O V E R";
int length = (int) g.getFontMetrics().getStringBounds(s, g).getWidth();
g.drawString(s, (WIDTH - length) / 2, HEIGHT / 2);
//  s = "Final Score: " + userPlayer.getScore();
length = (int) g.getFontMetrics().getStringBounds(s, g).getWidth();
g.drawString(s, (WIDTH - length) / 2, HEIGHT / 2 + 30);
gameDraw();

}

private void gameUpdate() {

 // new wave

  // create enemies
  /*
   if(waveStart && enemies.size() == 0) {
   createNewEnemies();
   }
   */
  // player update
  userPlayer.update();

  // bullet update
  /*
   for(int i = 0; i < bullets.size(); i++) {
   boolean remove = bullets.get(i).update();
   if(remove) {
   bullets.remove(i);
   i--;
   }
   }
   */

  /*
   // enemy update
   for(int i = 0; i < enemies.size(); i++) {
   enemies.get(i).update();
   }
   */
  // powerup update

  /*
   for(int i = 0; i < powerups.size(); i++) {
   boolean remove = powerups.get(i).update();
   if(remove) {
   powerups.remove(i);
   i--;
   }
   }
   */

  /*
   *
   // explosion update
   for(int i = 0; i < explosions.size(); i++) {
   boolean remove = explosions.get(i).update();
   if(remove) {
   explosions.remove(i);
   i--;
   }
   }

   */

  // text update

  for(int i = 0; i < texts.size(); i++) {
    boolean remove = texts.get(i).update();
    if(remove) {
      texts.remove(i);
      i--;
    }
  }

  // bullet-enemy collision

  /*
   for(int i = 0; i < bullets.size(); i++) {

  Bullet b = bullets.get(i);
  double bx = b.getx();
  double by = b.gety();
  double br = b.getr();

   for(int j = 0; j < enemies.size(); j++) {

   Enemy e = enemies.get(j);
   double ex = e.getx();
   double ey = e.gety();
   double er = e.getr();

   double dx = bx - ex;
   double dy = by - ey;
   double dist = Math.sqrt(dx * dx + dy * dy);

   if(dist < br + er) {
   e.hit();
   bullets.remove(i);
   i--;
   break;
   }

   }

   }
   */

   /*
  // check dead enemies
  for(int i = 0; i < enemies.size(); i++) {

  if(enemies.get(i).isDead()) {

   Enemy e = enemies.get(i);

  // chance for powerup
  double rand = Math.random();
  if(rand < 0.001) powerups.add(new PowerUp(1, e.getx(), e.gety()));
  else if(rand < 0.020) powerups.add(new PowerUp(3, e.getx(), e.gety()));
  else if(rand < 0.120) powerups.add(new PowerUp(2, e.getx(), e.gety()));
  else if(rand < 0.130) powerups.add(new PowerUp(4, e.getx(), e.gety()));

  player.addScore(e.getType() + e.getRank());
  enemies.remove(i);
  i--;

  e.explode();
  explosions.add(new Explosion(e.getx(), e.gety(), e.getr(), e.getr() + 30));

  }

  }
  */
  // check dead player
  /*
 if(userPlayer.isDead()) {
 running = false;
 }
 */

  // player-enemy collision
  /*
 if(!player.isRecovering()) {
 int px = player.getx();
 int py = player.gety();
 int pr = player.getr();
 for(int i = 0; i < enemies.size(); i++) {

 Enemy e = enemies.get(i);
 double ex = e.getx();
 double ey = e.gety();
 double er = e.getr();

 double dx = px - ex;
 double dy = py - ey;
 double dist = Math.sqrt(dx * dx + dy * dy);

  if(dist < pr + er) {
   player.loseLife();
  }

  }
  }
  */
  // player-powerup collision
  /*
  int px = player.getx();
  int py = player.gety();
  int pr = player.getr();

  for(int i = 0; i < powerups.size(); i++) {
  PowerUp p = powerups.get(i);
  double x = p.getx();
  double y = p.gety();
  double r = p.getr();
  double dx = px - x;
  double dy = py - y;
  double dist = Math.sqrt(dx * dx + dy * dy);

  // collected powerup
  if(dist < pr + r) {

   int type = p.getType();

   if(type == 1) {
   player.gainLife();
   texts.add(new Text(player.getx(), player.gety(), 2000, "Extra Life"));
   }
   if(type == 2) {
   player.increasePower(1);
   texts.add(new Text(player.getx(), player.gety(), 2000, "Power"));
   }
   if(type == 3) {
   player.increasePower(2);
   texts.add(new Text(player.getx(), player.gety(), 2000, "Double Power"));
   }
   if(type == 4) {
   slowDownTimer = System.nanoTime();
   for(int j = 0; j < enemies.size(); j++) {
   enemies.get(j).setSlow(true);
   }
   texts.add(new Text(player.getx(), player.gety(), 2000, "Slow Down"));
   }

   powerups.remove(i);
   i--;

   }

   }
   */

    }

     private void gameRender() {

    // draw background
       g.setColor(new Color(0, 100, 255));
       g.fillRect(0, 0, WIDTH, HEIGHT);

       // draw slowdown screen

       // draw player
       userPlayer.draw(g);

       // draw bullet

       /*
        for(int i = 0; i < bullets.size(); i++) {
        bullets.get(i).draw(g);
        }

        // draw enemy
        for(int i = 0; i < enemies.size(); i++) {
        enemies.get(i).draw(g);
        }

        // draw powerups
        /*
        for(int i = 0; i < powerups.size(); i++) {
        powerups.get(i).draw(g);
        }
        */
       /*
        // draw explosions
        for(int i = 0; i < explosions.size(); i++) {
        explosions.get(i).draw(g);
        }

        // draw text
        for(int i = 0; i < texts.size(); i++) {
        texts.get(i).draw(g);
        }

          // draw player lives
          for(int i = 0; i < player.getLives(); i++) {
          g.setColor(Color.WHITE);
          g.fillOval(20 + (20 * i), 20, player.getr() * 2, player.getr() * 2);
          g.setStroke(new BasicStroke(3));
          g.setColor(Color.WHITE.darker());
          g.drawOval(20 + (20 * i), 20, player.getr() * 2, player.getr() * 2);
           g.setStroke(new BasicStroke(1));
           }

           // draw player power
           g.setColor(Color.YELLOW);
           g.fillRect(20, 40, player.getPower() * 8, 8);
           g.setColor(Color.YELLOW.darker());
           g.setStroke(new BasicStroke(2));
           for(int i = 0; i < player.getRequiredPower(); i++) {
           g.drawRect(20 + 8 * i, 40, 8, 8);
           }
           g.setStroke(new BasicStroke(1));

           // draw player score
           g.setColor(Color.WHITE);
           g.setFont(new Font("Century Gothic", Font.PLAIN, 14));
           g.drawString("Score: " + player.getScore(), WIDTH - 100, 30);
           */

              }

            private void gameDraw() {
              Graphics g2 = this.getGraphics();
              g2.drawImage(image, 0, 0, null);
              g2.dispose();
             //  adapter.render(g);
            }

            public void keyTyped(KeyEvent key) {}
            public void keyPressed(KeyEvent key) {
              int keyCode = key.getKeyCode();
              if(keyCode == KeyEvent.VK_LEFT) {
                userPlayer.setLeft(true);
              }
              if(keyCode == KeyEvent.VK_RIGHT) {
                userPlayer.setRight(true);
              }
              if(keyCode == KeyEvent.VK_UP) {
                userPlayer.setUp(true);
              }
              if(keyCode == KeyEvent.VK_DOWN) {
                userPlayer.setDown(true);
              }
              /*
               if(keyCode == KeyEvent.VK_Z) {
               userPlayer.setFiring(true);
               }
               */
            }
            public void keyReleased(KeyEvent key) {
              int keyCode = key.getKeyCode();
              if(keyCode == KeyEvent.VK_LEFT) {
                userPlayer.setLeft(false);
              }
              if(keyCode == KeyEvent.VK_RIGHT) {
                userPlayer.setRight(false);
              }
              if(keyCode == KeyEvent.VK_UP) {
                userPlayer.setUp(false);
              }
              if(keyCode == KeyEvent.VK_DOWN) {
                userPlayer.setDown(false);
              }
              /*
               if(keyCode == KeyEvent.VK_Z) {
               userPlayer.setFiring(false);
               }
               */
            }
            // for mouse. MOUSE PROGRESS FTW!

            public void mouseClicked(MouseEvent e) {

            }
            public void mouseExited(MouseEvent e) {

            }
            public void mouseEntered(MouseEvent e) {

            }
            public void mousePressed(MouseEvent e) {
    playerPoint = e.getPoint();
     float angle = (float)(Math.atan2(userPlayer.gety() - playerPoint.y, userPlayer.getx() - playerPoint.x));
    int x = e.getX();
    int y = e.getY();
            }
            public void mouseReleased(MouseEvent e) {
     playerPoint = null;

            }
            public void mouseMoved(MouseEvent e) {
              int x = e.getX();
              int y = e.getY();
              float angle = (float)(Math.atan2(userPlayer.gety() - playerPoint.y, userPlayer.getx() - playerPoint.x));
   // ^^^ p used to be mouse so watch out on that.
    }
            public void mouseDragged(MouseEvent e) {
  turretPoint = e.getPoint();
    float angle = (float)(Math.atan2(userPlayer.gety() - turretPoint.y, userPlayer.getx() - turretPoint.x));
            }

            Ship sampleShip = new Ship(83,83,83,0,0,false,"C:\\Users\\Kenny\\Desktop\\ProjectProto\\ProtoGame\\Proto\\Images\\Ships\\ATN_FIGHTER_LOWRES.PNG");
           //TODO: have file directory change to allow other devices to be able to get the files.
    }

```

Camera.

```
  import java.awt.*;

  public class Camera{
  private int x,y;
  private Player player;
  private int xPos, yPos;
  MapSector sec;
   GameData data;
  public  int xmax = sec.XSIZE;
  public int ymax = sec.YSIZE;
  public int dist = 1;
  // prototype of the mouse location information.
  private  PointerInfo a;
  private Point b;
  private int mX,mY,cX,cY;
 private int dirX

  public int xView;
  public int yView;

  //Location of the center of an Image
  private  int iX, iY;
  public Camera(int x, int y, Player player, int xPos,int yPos){
    this.x = x;
    this.y = y;
    this.player = player;
    xPos = player.getx();
    yPos = player.gety();
    xView = data.WIDTH;
    yView = data.HEIGHT;
    iX = player.ship.img.getCenterX();
    iY = player.ship.img.getCenterY();
  }

  public int getX(){return x;}
  public int getY(){return y;}

  public void setX(int x){this.x = x;}
  public void setY(int y){this.y = y;}

  public void updateCamera(){
    a = MouseInfo.getPointerInfo();
    b = a.getLocation();
    mX = (int)b.getX();
    mY = (int)b.getY();
    cX = (mX - xPos) * dist + xPos;
    cY = (mY - yPos) * dist + yPos;
  }

  public void defaultCamera(){
    cX = iX;
    cY = iY;
  }

```

# Answer
> 1 votes
Lets start of by defining a few variables. Lets say that **o** is the position of the player, **d** is the point that we want the player to look at, **c** is the position of the camera and **dist** is how much do we want to move **c** towards **d**, were **dist** is a float between 0 and 1.

```
float cX = (dX - oX) * dist + oX;
float cY = (dY - oY) * dist + oY;

```

In case you want to move smoothly towards that point you can use the following method, where **L** the previous camera position, **C** is the one we just calculates using the method above, **out** is the smooth position, and **minDist** the distance from **C** that when reached the camera will stop moving:

```
float dirX = (cX - lX);
float dirY = (cY - lY);
float length = (float)Math.sqrt(dirX * dirX + dirY * dirY) - 0.6f;
dirX /= length;
dirY /= length;
dirX *= delta;
dirY *= delta;
float outX = lX + dirX;
float outY = lY + dirY;

```

In sum, all of the above would look something like this:

```
float cX = (dX - oX) * dist + oX;
float cY = (dY - oY) * dist + oY;

float dirX = (cX - lX);
float dirY = (cY - lY);
float length = (float)Math.sqrt(dirX * dirX + dirY * dirY) - 0.6f;

float outX = lX;
float outY = lY;

if(length > minDist) {
    dirX /= length;
    dirY /= length;
    dirX *= delta + 0.5f;
    dirY *= delta + 0.5f;
    outX = lX + dirX;
    outY = lY + dirY;
}

```

Now, in your case there are a few things you should change:

```
public void updateCamera(){
 a = MouseInfo.getPointerInfo();
 b = a.getLocation();
 mX = (int)b.getX();
 mY = (int)b.getY();
 cX = (mX - xPos) * dist + xPos;
 cY = (mY - yPos) * dist + yPos;

 float dirX = (cX - lX);
 float dirY = (cY - lY);
 float length = (float)Math.sqrt(dirX * dirX + dirY * dirY) - 0.6f;

 float outX = lX;
 float outY = lY;

 if(length > minDist) {
     dirX /= length;
     dirY /= length;
     dirX *= delta + 0.5f;
     dirY *= delta + 0.5f;
     outX = lX + dirX;
     outY = lY + dirY;
 }
 x = (int)outX;
 y = (int)outY;
}

```

Also, before you ask: I have taken a look at your code and haven't found the camera being used anywhere. So I thought you were having problems with that as well. Here is a solution: You can add an x and y offset to the position of every thing that is rendered, like entities and the player, but not the UI. And in each update you set that x and y offset to the **negative** x and y position of the camera. In that way the world will move around, creating the feeling that there is a camera.

---
Tags: java, 2d, camera, scrolling
---


# Question
Title: In gamemaker studio, how do I make text boxes?
How to make text boxes in gamemaker studio?

# Answer
There are the built-in functions to show textboxes to the user:

Read more here.
> 2 votes

---
Tags: game-maker, text
---


# Question
Title: Some OpenGL code not working, but some is
I'm just starting out using GLEW and GLFW in a C++ project for my rendering code, but I'm having trouble actually getting anything to render.

I know OpenGL is working in *some* capacity, because I am able to change the background colour, but nothing else is working beyond that.

I'm setting up the OpenGL context with this code:

```
    //Attempts to initiate GLFW. If it doesn't, it returns immediately
    if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return;
    }

    //glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

    window = GLFWwindowPtr();
    window.reset(glfwCreateWindow(width, height, windowTitle, NULL, NULL), DeleteWindow);

    if (window.get() == nullptr) {
        fprintf(stderr, "Failed to open GLFW window\n");
        glfwTerminate();
        return;
    }

    glfwMakeContextCurrent(window.get());

    glewExperimental = GL_TRUE; // Needed in core profile
    int errorCode = glewInit();
    if (errorCode) {
        printf("%i", errorCode);
        fprintf(stderr, "Failed to initialize GLEW\n");
        return;
    }

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glfwSwapBuffers(window.get());

```

A little while after that in my main loop, I call this code every frame:

```
float ratio;
int width, height;

glfwGetFramebufferSize(WindowHandler::getMainWindowGLPointer(), &width, &height);
ratio = width / (float)height;
glViewport(0, 0, width, height);
glClearColor(red / 255, green / 255, blue / 255, 1.0);
glClear(GL_COLOR_BUFFER_BIT);

```

Now this code works. I'm incrementing the red, green and blue variables every frame so that I can check that OpenGL is working as a whole and I see the background colour change.

However, when I put the following code after it, I'm seeing nothing different appear.

```
glBegin(GL_QUADS);              // Each set of 4 vertices form a quad
glColor3f(red/255, green/255, blue/255); // Red
glVertex2f(-0.5f, -0.5f);    // x, y
glVertex2f(0.5f, -0.5f);
glVertex2f(0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();

```

I used the code from an existing example found on https://www3.ntu.edu.sg/home/ehchua/programming/opengl/CG\_Introduction.html so I had a better chance of it being something in my implementation and not me messing up trying to write OpenGL code.

# Answer
> 2 votes
Thats because `glBegin`, `glVertex2f` and `glColor3f` are legacy functions which are deprecated. You may still use them if you request a backwards-compatible context, however I'd recommend you stick to your core-context (which is **not** backwards compatible) and learn the more powerful modern OpenGL.

There is a pretty good modern OpenGL tutorial series on opengl-tutorial.org, since you've already created the window and set up your context you can start by drawing your first triangle.

---
Tags: opengl, c++, glfw, glew
---


# Question
Title: How do you lock the camera down in ZBrush?
I'm trying to sculpt a tileable mesh on a flatplane and I keep inadvertently moving the camera when I go off canvas. Is there a way to lock the camera in place?

# Answer
You can save a camera angle using

Document\>ZApplink properties\> Then either choose front or Cust1

If you accidentally move your camera just navigate back to ZApplink properties and choose the camera you saved, it will snap the camera back to the saved position.
> 1 votes

---
Tags: zbrush
---


# Question
Title: GameMaker : how can i get the instance ID of multiple instance in a radius?
GameMaker and coding noob here, need help on something maybe trivial for some of you.

I'm working on the map part of a game. I have a map with spots on it, each spot is an instance of the same object.

I need to draw lines connecting the current spot and the close ones given a maximum distance (100 pixel radius). Also, I need to remove those lines that cross each other, and to keep track of which lines I already traveled.

I made an object `ctr_obj` that moves (on mouse click) from one spot to another if they are distant less than 100 pixels.

***Create Event* code :**

```
smp = instance_nearest(x,y,map_spot)
x = smp.x;
y = smp.y;

```

***Draw Event* code :**

```
for (i=0; i<instance_number(map_spot); i+=1)
{
    mapSpot[i] = instance_find(map_spot,i);
    near[i] = instance_nearest(x,y,map_spot)
    if point_distance(mapSpot[i].x,mapSpot[i].y,near[i].x,near[i].y)<100
    {
        draw_line(mapSpot[i].x,mapSpot[i].y,near[i].x,near[i].y)
    }
}

```

This part works as intended, I got the line drawn between the spot object I'm currently in and the other closest spot.

Ideally, I need to have all the lines of the map drawn all the time, not only when my `ctr_obj` is on a spot, and to keep track of the already traveled line (by changing its color, for example).

I tried to do something like that directly on the draw event of the `map_spot` object.

***Draw Event* code :**

```
for (i=0; i<maxnumber; i+=1)
{
    inst[i]= collision_circle(x,y,100,map_spot,false,false);
    if inst[i] !=noone
    {
        inst[i].x +=1000000;
    }
}
for (i=0; i<maxnumber; i+=1)
{
    if inst[i] !=noone
    {
        inst[i].x-=1000000;
    }
}
for (i=0; i<maxnumber; i+=1)
{
    draw_set_color(c_gray);
    draw_line(x, y, inst[i].x, inst[i].y)
    if done=1 && inst[i].done=1
    {
        draw_set_color(c_lime)
        draw_set_alpha(0.8)
        draw_line(x, y, inst[i].x, inst[i].y)
    }
}

```

It was the only way I found to be able to get the instance\_ID of multiple instances of the same object around a point. But as the event run on all `map_spot` I can't find a way to keep track of everything.

`done` is a variable to check if I already got on a particular spot. It doesn't really work as intended as if there are three map spots close enough each other I get a green triangle and not just the path used. And some paths don't get draw at all.

Can someone give me an hint?

**EDIT 1 :** So I try the solution, but something is not working. based on the solution provided, this is what I've done :

**the script i use :**

```
///scr_find_near(dist,object)

var list = ds_list_create();
with (argument1)
{
if (point_distance(x,y,other.x,other.y) < argument0)
    ds_list_add(list,other.id);
}
return list;

```

**the draw\_event code of the map\_spot object :**

```
closeList = scr_find_near(300,map_spot);
nb_near= ds_list_size(closeList)-1;

for (i = 0; i < nb_near; i += 1)
{
mp[i] = ds_list_find_value(closeList,i);
draw_set_alpha(1);
draw_set_color(c_gray);
draw_line(x,y,mp[i].x,mp[i].y);
info = string("nb of close point"+string(nb_near));
}

```

the "nb of close point" is just used as a debug for now (i have an "info" tool-tip for debug on all my objects). i try at first with mp as a "normal" variable, not an array, but actually nothing get draw. i can see that each point got the good number of "nb of close point" with the tool-tip, so the ds\_list got the good number of info stored in.

but i don't have any line between the map\_spot. I'm pretty sure i missed something obvious at this point, i spend too much time on that and can can't see clearly what i need to do. the script you give me work perfectly, but i think i made a mistake in my way of trying to use it to draw the line...

**EDIT 2** I continue my trial and error, with the code below on the map\_spot draw\_event :

```
with (map_spot){
if point_distance(x,y,other.x,other.y)<300
{
    draw_set_color(c_gray)
draw_line(x,y,other.x,other.y);
if (done=1 && other.done=1)
{
 draw_set_color(c_lime);
 draw_line(x,y,other.x,other.y);
 } } }

```

All the line between close spot are now correctly draw. That's a win. But i got my initial issue with keeping track of witch line have been traveled thru. Obviously, with the code above, all the line between map\_spot that have been visited are now green, not just the one i really "used".

the red number are the order of the map\_spot i click on the map. the orange X mark the line that i don't want to be green.

I need to try with a global variable to keep track of the number of movement (i will need to keep track of that for other reason) maybe it can help me draw only the green line i want.

already thx for the help, i'm closer than before to make it work !

EDIT 3 :

I manage to get it to work, not with a DS\_grid, i use a simple way (for me at least). I already had an invisible ctr\_object that move when i clic on a node where i can go (checking distance) this object "ctr\_map\_position" had multiple usefull variable for my game map ; the ctr\_map\_position step event :

```
if (x != xprevious && y != yprevious)
    {
    moveCount+=1;
    parSec += 0.1*point_distance(x,y,xprevious,yprevious)
    }

```

with that i keep track of the number of move(moveCount) and the total distance traveled in space (parSec). at each map\_spot, i transfert the current moveCount value to a variable named "place" on the map spot, witch tell me the position of the map spot in the journey. (1,2,3,4 etc..) Finally I draw green line only between map\_spot with variable 'place' = n and n+1

everything is now working as i intended to, so thx a lot for the help. obviously a ds\_grid or an array like you say may be more optimized but i'm still learning with this project, and optimization is not currently my priority ! (even if i try to do think the best way possible)

# Answer
> 1 votes
I'm not sure about what you're trying to achieve, but I can help with your starting question: how to get the `id`s of nearby instances, given an `object_index` to look for.

The idea behind is: given a radius *r* (in your case, 100 pixels), there may be more than one instance which is distant less than *r* from a reference object. So, we have two properties to find out the instances we are looking for: their `object_index`, and their distance from us.

```
// Look for those instance closer than 100 px
list = ds_list_create();
with (map_spot)
{
    if (point_distance(x,y,other.x,other.y) < 100)
        ds_list_add(other.list,id);
}

```

If you put this code into a script file, let's say `scrFindNearby`, you can call it as a function from GML like this:

```
scrFindNearby();

```

By doing this, the instance variable `list` will store in a `ds_list` the `id`s of those instances closer than 100 pixels to the instance that called the function. At this point, you can do whatever you want with them. Also, you can edit the function above to save both `id` and distance into two separate `ds_list`s or even better a `ds_grid` or, if you aren't familiar with data structures, you can use arrays too.

Hope that helps. :)

### EDIT 1

I can help with your problem drawing the right colour for lines. I figured out each `map_spot` has this variable `done`, which tells us if the spot has been visited before or not, so my answer is based upon this assumption.

Studying a path or a grid to figure out its properties, this is called graph theory. From now on, I'll call your `map_spot`s *nodes*, and the lines connecting two spots *arcs*. In the second picture you uploaded, you created the eight nodes in crescent order, so green arcs are drawn between arcs 1 and 2, 2 and 3, and so on to arcs 7 and 8. This is correct, because you traveled to arc *n* coming from arc *n-1*, and the connecting line was crossed.

You were expecting gray lines connecting nodes 2 and 4, and nodes 3 and 8. So, why are they green? Easy: you are drawing lines using the wrong criteria. Lines are drawn gray or green depending on the wrong information. Why? Because you are tracking if a node was visited or not, but you need to know whence it was visited too.

Node (`map_spot`) labeled '4' was visited from node '3', then a green line is drawn. Being node '4' close enough to node '2', then we can draw a line here too. Node '2' was visited from node '1', so node '2' is marked as *visited*, and so is node '4'. That means the line connecting '2' and '4' should be green, because they both were visited!

This is correct according to the algorithm logic, but we know it's wrong from our perspective: that line should be gray, because nodes '2' and '4' have been visited, sure, but node '4' *wan not visited from node '2'*, and vice versa.

I suggest you to keep the variable `done` for your `map_spot` objects, that will help you to keep track of which spots have been actually visited. In addition, you need a proper data structure to keep track of the paths you traveled through or not; each path (or line) can be identified with a starting point and an ending point, as those points are spots in the map. A two-dimensional array, or even better a `ds_grid`, are fine to hold this kind of information. This variable should belong to a controller object, or you can make it `global` if you want to.

For example, if you implement correctly a 2D-array to track the lines statuses, you may get something similar to this (based on the second image in your post):

```
/* Lines status matrix */
lines[0,0] = 1;     // Node 1 visited from node 1 (self-connected)
lines[0,1] = 1;     // Node 2 visited from node 1
lines[0,2] = -1;    // Node 3 can't be visited from node 1
lines[1,2] = 1;     // Node 3 visited from node 2
lines[1,3] = 0;     // Node 4 not visited from node 2 (as you expected)
...
lines[2,7] = 0;     // Node 8 not visited from node 3 (as you expected)

```

If this data structure is used, your draw code would look like this:

```
// Draw Event
with (map_spot)
{
    if (point_distance(x,y,other.x,other.y) < 300)
    {
        draw_set_color(c_gray);
        draw_line(x,y,other.x,other.y);
        if (ctrSpots.lines[index,other.index]==1)
        {
            draw_set_color(c_lime);
            draw_line(x,y,other.x,other.y);
        }
    }
}

```

Be careful when dealing with 2D-array or `ds_grid` indexes, you must always check the max number of instances before proceeding with drawing, and the data structure must be always be updated every time you add or remove a spot.

# Answer
> 2 votes
To answer the question in the title, any of GM's collision-testing functions will only return one instance, so you need to get creative to retrieve more than one.

The best solution I've found (and I use this to ensure that my attacks hit multiple targets if more than one is collided with in a single step) is to disable the collision of instances that you've already dealt with before re-running your test to find the next instance. Be sure to restore collision before leaving this code so that you don't create any unintended consequences later in the step.

To achieve this, do the following:

* Create a sprite with no image and no collision (let's call it no\_mask).
* On whatever object is running the collision test, create a 2d array.
* Wherever you're testing collision, create a loop to iterate through potential collisions.
* After getting a valid instance, store its id and its current mask\_index in the array, then change its mask\_index to that of the sprite you created that has no image/collision (no\_mask). The next collision test you perform won't be able to return this instance because it won't be collidable.
* Run whatever code you would on or with the instance that was collided with. After all instances are handled, allow the loop to end.
* Iterate through the array you just built with another loop and restore each instance's mask\_index from the array.

If you don't want to use a 2d array, create a mask property on the object you're testing for and use it to restore the mask\_index to each instance.

Hope this helps.

---
Tags: path-finding, game-maker
---


title: Why can't game be easily adapted to VR

text:
# Question
Title: Why can't game be easily adapted to VR
I've had this question for some time now, but never got around to asking it. Why can't games be easily adapted to VR? I understand some games in which animations change viewpoint would nauseate the gamer, but in games like CSGO, where the only thing that would be difficult might be scoping in and head bob, why can't games simply go through some predetermined algorithm to split the view for VR, and add in code for VR headset control and VR controllers? I assume there is some reason, but I can't think why.

Thanks for any help.

# Answer
> -3 votes
If your game character moves forward in VR without you physically moving, your brain will get confused and you will get motion sick. Most VR games get around this by teleporting you so you don't really "move", but this requires the games to be made for VR.

---
Tags: virtual-reality
---


# Question
Title: How to transition to a different animation during the blend phase?
I have a set of animations: Idle, start walking, stop walking, and walking full speed.

I have the animations all blending nicely...and the controls are fairly responsive during most of the motion...but there are odd transitions where the blends take away control--I can't transition to the walking animations when I am blending between the "stop walking" and "Idle" animations, for instance.

How do I get the animations to transfer during the blend phase??

# Answer
If your character controller have variable movement speed value, use it for blending.

Are you using any transition/condition to exit the blend tree and enter into another blend tree?

Use movement float value for transitioning between blend trees as you normally use between states.
> 0 votes

---
Tags: animation, unity
---


title: Accelerating Missile guidence

text:
# Question
Title: Accelerating Missile guidence
### Background

I'm building a simple game where two ships are launching missiles at each other in space.

Stuff got complicated when the ships started moving in a frictionless environment and the missiles naturally needed to do the same thing.

### Premises

1. A missile has a constant acceleration and is trying to hit a moving target in a frictionless environment.
2. Target is also constantly accelerating in the same frictionless environment.
3. The frictionless environment is only 2 dimensional
4. There is no gravitation affecting the missile

### Question

What math should I use to determine the direction the missile should jolt in?

### What i have right now

I've implemented this answer which works quite alright. I am not 100% sure of what a, b, c etc means and not sure which math is actually implemented here.

I modified above linked answer by making the missile mimmic its targets jolts and adding its own on top of those. It is an ugly solution to say the least.

### Problem with current solution

The current solution requires to know the speed of the missile.

The missile is constantly accelerating, and it has no top speed.

Unless I know how far the missile will travel, *I cannot know the average speed.*

Above solution requires that I know the speed of the projectile.

# Answer
## A probing solution

I am sure there is a better solution using some clever math, but until you get **that** answer you can try this.

### What you can calculate

You know the position, current speed and acceleration of the enemy and can calculate where it will be in the future.

You also know the position, current speed and acceleration of the missile and can calculate where it will be in the future, if you just knew the direction to go.

### Iterating calculation

Now we can start to calculating the direction where to aim the missile like this:

1. Set the first time in the future to calulate (in the graph 1 sec)
2. Calculate the position of the enemy
3. Aiming at the position of the enemy, calculate the position of the missile
4. Calculate the distance of the missile and the enemy. Use the distance to check if it is near enough (using a threshold distance). Also keep this distance to compare with the next iteration (we want to know if the distance starts to get longer)
5. If distance was close enough we have a direction and can break the iteration. If the distance gets longer then the last iteration was the best direction and we can break the iteration
6. We haven't found the solution yet, increase the time value (+1 sec in the graph) and go back to number 2 in the list

*This shows three iterations for the calculation of one, two and three seconds in to the future. The third one was close enough regarding the threshold in this example and the direction was selected.*
> 1 votes

---
Tags: projectile-physics
---


# Question
Title: What is the velocity of a translating projectile in 2D?
**What I'm trying to do.**

So I want to have a projectile that starts at point (x1, y1) and *head in the direction of my mouse say point* (x2, y2).

To clarify I'm pretty sure it's a vector but I don't know much about them.

**Language / Librarys**

I'm making the game in Java and LibGDX so Java.MathUtils would come in to play i'm pretty sure. If anyone that can answer don't know these languages, psuedocode will be just fine.

**How I've tried it**

I'm pretty sure the formula is something alongs the lines of velX := cos(radians) * speed velY := sin(raidans) * speed

And radians starts out as Pi/2 though the tutorial was pretty rough.

Then it would be x += velx * deltatime and same with y.

**Can anyone help me out with the translation formula**

# Answer
> 3 votes
You need to learn a little bit more about vectors but I'm going to explain it anyways.

First of all, let's say that your 'game unit' is in *pixels* and that `points` (coordinates) and `vectors` have *two components* `x` and `y`.

Let's assume that you have two given `points` A = (x1, y1) and B = (x2, y2).

To get the vector between A and B, you have to do the following formula: `V = B - A`. Since B and A have two components, we can translate this into `V = (xB-xA, yB-yA)`

However, this vector is pretty much useless because the length of it is the length of the line between A and B. If you have something like this

```
V = mouse.pos - projectile.pos
projectile.pos += V

```

it will instantly move the projectile to the mouse because - well - you're asking to move the projectile to the mouse..

The idea here is to get a `direction` from your projectile (point A) to your mouse or whatever object (point B).

So.. how do we get this direction ? Well, it's easy, the formula is `u = V/length(V)`

This procedure is `normalizing` where you just get the `direction` of a vector and completely ignore its length (sometimes called 'magnitude').

Adding this vector `u` to your position will move your object **1 unit** away from its current position.

The point of it ? Moving your projectile towards a point with a fixed 'speed', like this:

```
projectile.pos += u * 10;

```

this code will move your projectile **10 units** (let's say pixels) towards your mouse.

---

EDIT: Note that with this method you don't need to use trigonometry to compute the normalized vector; that means that neither you have precision loss (floats, pi, ...) nor confusing conversions with radians. That's a win :)

---

EDIT2: For consistence and clarity, I used the word vector and position but these "concepts" are the same: a point has an X and Y component as well as a vector.

In the code you would use the same data structure. Unfortunately I don't know java but I can provide you a c++ example:

```
struct MyData //That would be public class in java I beleive
{
    float x;
    float y;
}

```

Here MyData is a structure that allows two components: x and y. This structure is used for points as well as vectors; eg:

```
MyData point_a;
MyData point_b;
MyData vector_between;

//Instantiate and/or initialize values ...

vector_between = point_b - point_a;

```

In C++ there is a concept (operator overloading) that makes you able to perform custom operations between data structures (such as `point_b - point_a` in the above example). This is really useful because the program won't know how to subtract two "MyData" together unless you write your own method.

I don't think Java enables you to do this "hack", so instead of

```
vector_between = point_b - point_a;

```

you could write

```
vector_between.x = point_b.x - point_a.x;
vector_between.y = point_b.y - point_a.y;

```

this is what I meant where I directly used "pos" without the associated component.

Moreover, when I used `length(V)` I meant `sqrt(V.x*V.x + V.y*V.y)`, that is the *length/distance* between two points (Pythagorean theorem, right ?)

NB: Usually the `MyData` data structure is, by "convention" called a `Vector2` in 2D, `Vector3` in 3D etc...

# Answer
> 0 votes
To get from point `A` to point `B` where both A and B are vectors, the direction is the vector `normalize(B - A)`, lets call it `C`. The velocity you're looking for is the direction-vector `C` times the speed in units per second.

So if `A` is your actual position, `B` is your target position, `10` is the speed in units per second and `delta` is your deltatime, then your velocity is `velocity = normalize(B - A) * 10;` and your new position is `A + velocity * delta`.

---
Tags: java, libgdx, mathematics
---


# Question
Title: Altering Physics Property of a Shape in Unity
I want to create say 4 blocks, and each block will dictate how e.g. the bounciness of an object landing on it will behave. So if the block is made of sand, I don't want bounciness, if the block is wood I want it to bounce, if it's ice block i want it to bounce a bit and then slide for X amount of time. How can I adjust the physics of the object landing on that block based on what block it is?

# Answer
> 1 votes
Create four GameObjects. Add a Collider to each GameObject. Set the physics material of each Collider.

http://docs.unity3d.com/Manual/class-PhysicsMaterial2D.html

Set the bounciness to the value you want in the Physics Material. Each GameObject would have it's own physics material with specific bounciness.

---
Tags: unity, physics
---


title: KeyCode dictionary in Unity

text:
# Question
Title: KeyCode dictionary in Unity
I found a strange problem while programming keyboard input in Unity (v5.3.5).

```
public class AvatarInputMapperUnityContext : MonoBehaviour {

    private AvatarController _avatarController;

    public KeyCode JumpKey = KeyCode.Space;
    public KeyCode LeftKey = KeyCode.A;
    public KeyCode RightKey = KeyCode.D;
    public KeyCode UpKey = KeyCode.W;
    public KeyCode DownKey = KeyCode.S;
    private Dictionary<KeyCode, WeaponTags> ShotKeys;

    void Awake () {
        _avatarController = GetComponent<AvatarController>();
        ShotKeys.Add(KeyCode.I, WeaponTags.Pistol);
        ShotKeys.Add(KeyCode.O, WeaponTags.Shotgun);
    }

    void Update () {

        if (Input.GetKeyDown(JumpKey)){
            _avatarController.JumpSignal();
        }
    }
}

```

Now, when the `ShotKeys.Add...` lines are commented out everything works fine. But when I uncomment them, the program never reaches the `_avatarController.JumpSignal()` line, and none of the other directional keys (w,a,s,d) work. What can be the reason?

# Answer
Init your Dictionary in your Awake first:

```
ShotKeys = new Dictionary<KeyCode, WeaponTags> ();

```
> 1 votes

---
Tags: unity, input, keyboard
---


# Question
Title: Maintain speed, in 3D game, after collision in Unity
I am making a simple breakout game. I have added bounce physics to the ball and to the bricks. When the ball collides with the bricks, the speed of ball slows down. I want ball to maintain its speed to what I set it to intially.

# Answer
Set a new Physics Material on both the ball and the object you are colliding with. Make sure you set the Friction parameters to 0 and Bounciness to 1.

(Alternatively, you can apply the material to just one side of the collision, with the Combine parameters set to "Maximum" so it overrides the material of anything it collides with)
> 1 votes

---
Tags: unity, collision-detection, physics
---


# Question
Title: How to achieve 2D ski movements similar to Alto Adventure?
I'm trying to achieve 2d movement similar to Alto's Adventure with Unity 2D. **When grounded I want the character to slide alone the terrain parallel to the slope, but I want to be able to freely rotate the character in mid air**. In my current failed implementation I tried using a 2d collider attached to an gameobject with a movement custom script. I'm using vertical and horizotal raycast to detect the slopes, and the object rotates based on the angle of the slope. Long story short I've given up on this implementation for now.

Do you guys have any suggestions or pointers on achieving this type of movement?

# Answer
> 1 votes
In Alto's Adventure, the terrain is dynamically generated over time, by concatenating prefabricated patterns (for example the super steep slope where you can perform a triple backflip, or any other soft slopes) in a randomic way to keep the game various from play to play.

A possible implementation can be treating these "pieces" of terrain as vertices, from which it is possible to compute normal vectors and set the facing direction of your snowboarder accordingly.

About distinguishing between sliding and jumping, you can perform some checking during each game step:

* If the user pressed/tapped for jump, perform the jump action. This applies if there's a collision underneath the player and only when key is pressed, not while it's being pressed;
* If there's a collision under the player model:
    + Change speed and direction of the player according to the direction of normal vector of the terrain - to draw the player standing upright;
* Else, if the player is mid-air:
    + If input key is being pressed, increase the drawing angle; if not, do nothing *or* change it to reach the right value to draw the player upstanding.

While the terrain is generated dynamically by jointing pre-made pieces of terraing, interacting objects - such as rocks, fireplaces, roofs, coins - are placed randomly so that they don't intersect each other (exception for coins, they can be both below or above a grind wire, for example).

---
Tags: unity, 2d, collision-detection, physics, movement
---


title: DirectX 12: Problem with render target

text:
# Question
Title: DirectX 12: Problem with render target
I've got a problem with DirectX 12 I cannot figure out by myself. I wrote a small program that should render a triangle onto the screen. When I executed the application, however, there was no triangle visible. So I launched NVidia's nsight debugger. The weird thing is that the triangle has been drawn to the depth-stencil buffer but not to the back buffer.

If I clear the render target view to light blue it would look like this:

If you need any code snippets please write it in the comments and I will post it.

Thanks in advance

# Answer
> 3 votes
Start graphics debugging (ALT+F5) your program with visual studio directX graphics diagnostic and capture a frame, then double click on the thumbnail of frame and view your event list and your pipeline. It will help you to find out whats really happening down there. May be you forgot to set and clear your render target view before drawing vertices.

read this article for better understanding: DirectX Graphics Diagnostic

---
Tags: directx, rendering
---


# Question
Title: How to calculate a simple swivel rotation? (no physics engine)
Assuming i know the geometry and the rotation angle of a cart, how can i calculate the rotation angle of a swiveling wheel?

To get the rotation angle of the wheel, i tried by calculating the distance from the rotation axis, and to apply a friction coefficient:

```
var dx = cartCX - wheelCX,
    dy = cartCY - wheelCY,
    dist = Math.sqrt(cartCX * wheelCX + cartCY * wheelCY);

var wheelRotation = Math.atan2(-dy, -dx) * dist * friction;

```

But all this has not brought me any acceptable result.

Which is a simple way to get the wheels rotation angle about the Y axis when the cart is rotating?

I don't need exact physics simulation, just a smooth rotation angle which i can tween. I think there should be no need to use any physics engine, or i'm wrong?

# Answer
> 1 votes
When in doubt: Fake it.

Instead of calculating the wheels from where the cart is, calculate the wheel direction from where the *wheel* was.

Something like this:

```
//Constants, per wheel. I'm assuming Y is up/down
var wheelOffset = Vector3( -40, 0, -10 );
//Variables kept over multiple frames, per wheel
var wheelAngle = 0;
var lastWheelPosition = 0;

//Per frame:
//Calculate the world position of the wheel from the carts transformation matrix, there's other ways if you don't use a matrix but a matrix is probably the most common to use
var wheelPosition = cartTransformation * wheelOffset;

//Calculate how much the wheel moved, from *this* we can then calculate an angle
var wheelDist = wheelPosition - lastWheelPosition;
var newAngle = Math.atan2( wheelDist.x, wheelDist.z );

//This is the final angle we use for this wheel. There's various tweaks you can do to get behaviour you want. The 0.1/0.9 variables adjust how fast a rotation of the cart is send to the wheels
wheelAngle = newAngle * 0.1 + wheelAngle * 0.9;

```

I may have some signs swapped, this is off the top off my head and not tested.

---
Tags: physics, javascript, rotation
---


# Question
Title: Can I develop a game using C++ and deploy to XBOX 360?
I'm a C# developer and an enthusiast of XNA, but I'm really disappointed with the game engines available for XNA.

I was using Torque X, which is really good, but GarageGames no longer supports Torque X for XNA 4.1. I searched for other engines, but only the sunburn was worth it and would have to pay - I already spent money with Torque.

Based on this, I'm thinking about starting to develop in C++. **Can I develop with some C++ engines and deploy to XBox 360?**

# Answer
> 8 votes
Simple answer. No. Unless you are a licensed developer with Microsoft (which costs thousands) then you will not be able to deploy C++ applications to the Xbox 360.

There might be some homebrew software out there somewhere to try and do it, but a) it's a legally grey area and b) it's more than likely to be completely subpar in handling the console's hardware capabilities.

EDIT: Just to add about engines. There are plenty of engines out there that support Xbox 360 as a development platform (Unity, Unreal Engine, etc) but they all have the precursor that you have a developer license.

# Answer
> 0 votes
You can, however, you must use proper Devkit, which is hard but not impossible. Just, apply for ID@XBOX and go learn it yourself.

And seriously, target steam first and show some traction. Or, pay a lot of bucks. Or, port to C# and go for it.

# Answer
> -4 votes
Any language will run on Xbox 360. There are games available that were programmed in C++ and Java. For example Google 'Minecraft Xbox 360 Edition Minecraft wiki'. It will say Minecraft for Xbox was written in C# and C++.

---
Tags: xna, c++, xbox
---


# Question
Title: Making a button that spawn objects in the world?
I want to make a button that can spawn an object that I've already created. Though I have no clue how to actually do this / where to start. Has anyone ever done something similar?

# Answer
In short - you track input events (whatever you have), and check if mouse/touch/whatever click coordinates is crossing sensing area that designate your button on screen. Then you call associated function that process this event.
Detailed answer will require explaining lots of very basic stuff (you didn't even name your windowing lib/framework/api), and you should learn that yourself.
> 3 votes

---
Tags: opengl
---


title: Behaviour tree editor Unity

text:
# Question
Title: Behaviour tree editor Unity
I'm a programmer, so I am perfectly aware of how to implement a behaviour tree. I don't want to rely on third party tools, but still have convenient tools for creating the AI for my game.

I was looking at tools like this one but I could not find out how to create editor extensions like that in Unity.

I also noticed that there is a new experimental feature (Playables) in the current versions of Unity.
Does this use the state machine editor from the Animator? Should/Could I use that to implement a behaviour tree?

# Answer
> 0 votes
The general topic you're interested in is editor scripting.

Here's Unity's start page for it: http://docs.unity3d.com/Manual/ExtendingTheEditor.html

Here's a tutorial they put together as well: https://unity3d.com/learn/tutorials/topics/scripting/editor-scripting-intro

Neither of those links deal directly with making a node based editor, which is likely what you want to do. I recommend you check them out though, as they'll give you some basics on extending the editor in general, which you'll need as a starting point.

Once you're familiar with the basics of editor scripting, you may find this useful: http://forum.unity3d.com/threads/simple-node-editor.189230/

---
Tags: unity
---


# Question
Title: Performance problem with BufferedImage and AlphaComposite
I'm currently making a 2D platformer game and now I want to implement Light using AlphaComposite. For creating the lights I first create a blank BufferedImage with ARGB format. After this, I create darkness by filling a black transparent rectangle over my screen. Now I am using `AlphaComposite.DST_OUT` and an image with an white cirle. When I render the white circle, the black darkness will be eliminated caused by the AlphaComposite. Lastly, I render this BufferedImage to my main BufferedImage where all the rendered stuff comes together. As you can see on the picture it works fine but when I resize my game it starts to lag extremely. Without using the light system the game actually runs perfect in fullscreen, as well.

Here is an extract of my code where I render my lights:

```
public void render(Graphics2D g) {
    BufferedImage image = new BufferedImage(GamePanel.width, GamePanel.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    g2.setColor(new Color(0,0,0,210));
    g2.fillRect(0, 0, GamePanel.width, GamePanel.height);

    Composite old = g2.getComposite();
    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_OUT, 1.0f);
    g2.setComposite(ac);
    g2.drawImage(Light.LIGHT, 50, 25, null); //here i render the image with the white cirle
    g2.setComposite(old);

    g.drawImage(image, 0, 0, null); //drawing lights to the main bufferedimage
}

```

The last line `g.drawImage(image, 0, 0, null);` is where I render the light to my main BufferedImage where all the rendered stuff is rendered, as well.

This is how I render my main BufferedImage:

```
@Override
public void paintComponent(Graphics g) {

    Graphics2D g2d = image.createGraphics();
    g2d.setBackground(new Color(146, 189, 221));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gamestatemanager.render(g2d);

    g.drawImage(image, 0, 0, width, height, null); //scaling the main bufferedimage
}

```

Do you have some Ideas for me?

**EDIT** The game also starts lagging in fullscreen when I just paint the black rectangle.

# Answer
> -1 votes
I found the answer:

My game is actually very small but I resize it by a scale factor of 4. So I also have to divide the width and height of my bufferedimage by 4 inside the light render method

```
public void render(Graphics2D g) {
BufferedImage image = new BufferedImage(GamePanel.width / SCALE, GamePanel.height / SCALE, BufferedImage.TYPE_INT_ARGB);

```

---
Tags: java, performance, lighting, platformer
---


# Question
Title: C# XNA AABB vs AABB collision resolution, AABBs ghost through each other
I've been learning a bit of collision resolution through a tutorial here and I can't seem to get the AABBvsAABB resolution working, I have CirclevsCircle and AABBvsCircle resolution working with the same method,`ResolveCollision`

Essentially what happens is I have a test scenario where two AABBs collide with each other. The collision gets detected however, the AABBs will just keep going through each other. If two circles collide, they show the correct response.

If you need the full code you can nab it from my github. This has both Windows and Linux versions.

Here is the data class that is passed to the `AABBvsAABB` method:

```
public struct Manifold
{
    public PhysicsObject A, B;
    public float PenetrationDepth;
    public Vector2 Normal;
    public bool AreColliding;
}

```

Here is the code for testing the collision between the AABB and AABB

```
public static bool AABBvsAABB (AABB a, AABB b, ref Manifold m)
{
    m.A = a;
    m.B = b;
    m.Normal = b.Position - a.Position;

    //Calculate the extent on the X axis
    float aExtent = (a.Right - a.Left) / 2;
    float bExtent = (b.Right - b.Left) / 2;

    //Find the X overlap
    float xExtent = aExtent + bExtent - Math.Abs (m.Normal.X);

    //SAT Test on X
    if (xExtent > 0) {
        //There was overlap on the X axis, now lets try to Y
        aExtent = (a.Bottom - a.Top) / 2;
        bExtent = (b.Bottom - b.Top) / 2;

        //Calculate Y overlap
        float yExtent = aExtent + bExtent - Math.Abs(m.Normal.Y);

        //SAT Test on Y axis
        if (yExtent > 0){
            //Find which axis has the biggest penetration ;D
            if (xExtent > yExtent){
                if(m.Normal.X < 0)
                    m.Normal = new Vector2(-1,0);
                else
                    m.Normal= Vector2.Zero;
                m.PenetrationDepth = xExtent;
                m.AreColliding = true;
                return true;
            }
            else {
                if(m.Normal.Y < 0)
                    m.Normal = new Vector2(0,-1);
                else
                    m.Normal= Vector2.Zero;
                m.PenetrationDepth = yExtent;
                m.AreColliding = true;
                return true;
            }
        }
    }
    return false;
}

```

Lastly here is the `ResolveCollision` Method.

```
public static void ResolveCollision(Manifold m)
{
    Vector2 relVelocity = m.B.Velocity - m.A.Velocity;
    //Finds out if the objects are moving towards each other.
    //We only need to resolve collisions that are moving towards, not away.
    float velAlongNormal = PhysicsMath.DotProduct(relVelocity, m.Normal);
    if (velAlongNormal > 0)
        return;
    float e = Math.Min(m.A.Restitution, m.B.Restitution);

    float j = -(1 + e)*velAlongNormal;
    j /= m.A.InvertedMass + m.B.InvertedMass;

    Vector2 impulse = j*m.Normal;
    m.A.Velocity -= m.A.InvertedMass*impulse;
    m.B.Velocity += m.B.InvertedMass*impulse;
}

```

# Answer
> 0 votes
I fixed the problem by putting a normalized normal into the `m.Normal` field and multiplied it by a value to flip the normal depending on what axis/axes it was intersecting on.

```
public static bool TestAABBvsAABB (AABB a, AABB b, ref Manifold m)
        {
            m.A = a;
            m.B = b;
            m.Normal = b.Position - a.Position;

            //Calculate the extent on the X axis
            float aExtent = (a.Right - a.Left) / 2;
            float bExtent = (b.Right - b.Left) / 2;

            //Find the X overlap
            float xExtent = aExtent + bExtent - Math.Abs (m.Normal.X);

            //SAT Test on X
            if (xExtent > 0) {
                //There was overlap on the X axis, now lets try to Y
                aExtent = (a.Bottom - a.Top) / 2;
                bExtent = (b.Bottom - b.Top) / 2;

                //Calculate Y overlap
                float yExtent = aExtent + bExtent - Math.Abs(m.Normal.Y);

                //SAT Test on Y axis
                if (yExtent > 0){
                    //Find which axis has the biggest penetration ;D
                    Vector2 fixnormal;
                    if (xExtent > yExtent){
                        if(m.Normal.X < 0)
                            fixnormal = -Vector2.UnitX;
                        else
                            fixnormal = Vector2.UnitX;

                        m.Normal = PhysicsMath.GetNormal(m.A.Position, m.B.Position) * fixnormal.X;
                        m.PenetrationDepth = xExtent;
                        m.AreColliding = true;
                        return true;
                    }
                    else {
                        if(m.Normal.Y < 0)
                             fixnormal = -Vector2.UnitY;
                        else
                            fixnormal= Vector2.UnitY;
                        m.Normal = PhysicsMath.GetNormal(m.A.Position, m.B.Position) * fixnormal.Y;
                        m.PenetrationDepth = yExtent;
                        m.AreColliding = true;
                        return true;
                    }
                }
            }

            return false;
        }

```

# Answer
> 2 votes
I believe that your manifold normals are incorrect. These AABBs will attempt to "push back" along the axis of the greatest intersection, however:

```
if(m.Normal.X < 0)
  m.Normal = new Vector2(-1,0);
else
  m.Normal= Vector2.Zero;

```

That code is saying "if B is further left than A, then the direction to resolve penetration is in the negative X axis, otherwise there is no direction."

Try changing the else block to:

```
else
  m.Normal = new Vector2( 1, 0 );

```

However this may still not do quite what you want (if you want the AABB to "bounce" off eachother more naturally.) In that case you will want to just compute the B - A and then normalize the vector. (It should have a method on the class to do so.)

Your resolution does not account for penetration depth either, so you will lose a lot of accuracy at greater timeslices.

# Answer
> 0 votes
I think I've seen some of your other posts as I followed the same tutorial myself here years later.

You've tried to "correct" the logic of the original algorithm by using

```
//Find which axis has the biggest penetration ;D
                    Vector2 fixnormal;
                    if (xExtent > yExtent){

```

But that's not the original tutorial's logic which has:

```
// Find out which axis is axis of least penetration

```

I had to draw out some cases on paper to understand, but, suppose you have two boxes, one above the other, separated by a small gap and traveling towards each other.

These boxes will overlap on the X-Axis, which is to say they can have almost total penetration if they are directly one above the other.

So if that's the case, the second test is to test along the y-axis. In this example it would fail because the two boxes don't overlap.

But, suppose now we "step" the simulation and the boxes move closer together such that a bit of overlap has occured... not much because we only step the simulation a few milliseconds at a time.

So now, we still have almost total X penetration, because one block is above the other... but we also have a liiiiitttle bit of Y penetration.... due to the collision.

So, we're trying to find the Axis of least penetration because that's the axis along which the collision just occurred.

Here's my copy (C++) of the AABBvsAABB algorithm.

```
bool AABBvsAABB(Manifold *m)
{

    // Setup a couple pointers to each object
    Box * A = dynamic_cast<Box *>(m->A);
    Box * B = dynamic_cast<Box *>(m->B);

    // Vector from A to B
    Vector2d n = B->_pos - A->_pos;

    AABB abox = A->aabb;
    AABB bbox = B->aabb;

    // Calculate half extents along x axis for each object
    double a_extent = (abox.max.x() - abox.min.x()) / 2;
    double b_extent = (bbox.max.x() - bbox.min.x()) / 2;

    // Calculate overlap on x axis
    double x_overlap = a_extent + b_extent - abs(n.x());

    // SAT test on x axis  ( Separating Axis Theorem )
    if (x_overlap > 0)
    {
        // Calculate half extents along x axis for each object
        double a_extent = (abox.max.y() - abox.min.y()) / 2;
        double b_extent = (bbox.max.y() - bbox.min.y()) / 2;

        // Calculate overlap on y axis
        double y_overlap = a_extent + b_extent - abs(n.y());

        // SAT test on y axis
        if (y_overlap > 0)
        {
            // Find out which axis is axis of least penetration
            //if (x_overlap > y_overlap) // TC: Suspect this logic was wrong implementation of comment above
            if (x_overlap < y_overlap)
            {
                // Create a Collision Manifold...

                // Point towards B knowing that n points from A to B
                // TC: Create a left of right "unit vector" normal
                if (n.x() < 0)
                    m->normal = Vector2d(-1, 0);
                else
                    m->normal = Vector2d(1, 0);
                //m->normal = Vector2d(0, 0);// TC: Suspect there was another bug here.

                if (BOXES_COLLIDE_LIKE_BALLS)
                {
                    m->normal = n.normalized();
                }

                m->penetration = x_overlap;
                return true;
            }
            else // x overlap is greater, so assume is a Y-Axis collision
            {
                // Point toward B knowing that n points from A to B
                // TC: Create either an up or a down vector.
                if (n.y() < 0)
                    m->normal = Vector2d(0, -1);
                else
                    m->normal = Vector2d(0, 1);

                if (BOXES_COLLIDE_LIKE_BALLS)
                {
                    m->normal = n.normalized();
                }

                m->penetration = y_overlap;
                return true;
            }
        }

    }

    // either x does not overlap, or does, but y does not... no collision
    return false;

```

}

I render my world using a down view of it... kind of like looking down on a pool table with balls and uh... boxes.

What baffled me for some time is that, in my example above, if two boxes travel towards each other at the same speed and aligned with each other, they would stop. It didn't make sense to me. But then I tried the same test with Circle vs Circle. Same thing happened... the balls collide and stop.

And then I realized that this is correct behaviour. If you could perfectly roll two billiard balls towards each other at the same speed, they would stop. (Of course it's next to impossible to achieve this kind of mathematical perfection in reality, but play enough pool and you'll see it happen on occasion.

The same thing applies to the physics being used in the tutorial here for boxes. It's simplistic, but the author mentions that in his explanation and it does indeed work.

---
Tags: xna, c#, collision-detection, resolution
---


title: WebGL Redirecting URL

text:
# Question
Title: WebGL Redirecting URL
If player's browser don't support WebGL, I want to redirect Web Player version. I think it's possible in UnityLoader.js file but how?

```
function CompatibilityCheck(){hasWebGL?mobile?confirm("Please note that Unity WebGL is not currently supported on mobiles. Press Ok if you wish to continue anyway.")||window.history.back():-1==browser.indexOf("Firefox")&&-1==browser.indexOf("Chrome")&&-1==browser.indexOf("Safari")&&(confirm("Please note that your browser is not currently supported for this Unity WebGL content. Try installing Firefox, or press Ok if you wish to continue anyway.")||window.history.back()):(alert("You need a browser which supports WebGL to run this content. Try installing Firefox."),window.history.back())}

```

I just want to add a URL redirect here.

# Answer
Just add this to the bottom of the HTML page that Unity generates for you BEFORE the Module declaration and UnityLoader.js is loaded (I wouldn't hack the UnityLoader.js file because it'll get overwritten every time you do a build).

```
<script>
    if (!window.WebGLRenderingContext) {
        window.location = "http://whatever.com";
    }
</script>

```

So it would look like this at the bottom of your index.html

```
<script>
        if (!window.WebGLRenderingContext) {
            window.location = "http://whatever.com";
        }
    </script>

<script type='text/javascript'>
  var Module = {
    TOTAL_MEMORY: 1610612736,
    errorhandler: null,         // arguments: err, url, line. This function must return 'true' if the error is handled, otherwise 'false'
    compatibilitycheck: null,
    dataUrl: "Release/Project.data",
    codeUrl: "Release/Project.js",
    memUrl: "Release/Project.mem",

  };
</script>
<script src="Release/UnityLoader.js"></script>

```
> 1 votes

---
Tags: unity, webgl, web, node.js, json
---


# Question
Title: Unity - Accessing a UI's text through a Transform
I have this in my player's component list. The HungerTarget transform is the text box in the UI canvas. How would I change the UI's text here?

```
using UnityEngine;
using System.Collections;

public class HealthHunger : MonoBehaviour {
    //public Transform HealthTarget; Not being used yet...
    public Transform HungerTarget;

void Start () {
}

void Update () {
    //set HungerTarget's text to ...
}

```

}

# Answer
> 0 votes
```
void Update () {
    HungerTarget.GetComponent<Text>().text = "Your text here";
}

```

# Answer
> 1 votes
Even better: change the type of your public variable!

```
using UnityEngine;
using UnityEngine.UI;

public class HealthHunger : MonoBehaviour {

    public Text hungerText;

    void Update() {
        hungerText.text = "your text here";
    }
}

```

You can still drag your UI Text gameObject into this `public Text` field in the inspector, and Unity will choose the Text component from it automatically.

This has some advantages:

* Unity will guarantee that whatever is assigned to that field has a `Text` component.
* This requirement is visible to a level designer working in the editor, clearly communicating what the script needs to function without needing to read the code.
* No need to call `GetComponent<Text>()` every frame, or to set aside a variable to cache the result after calling it once.
* You can still get the `Transform` when you need it by writing `hungerText.transform` \- this is substantially faster than a typical `GetComponent<>()` call, so you typically won't need to worry about caching this separately.

In general, when a script relies on an object referenced by an inspector field having a specific component, giving that field the specific type you want can help simplify the code and narrow down the types of bugs you might have to fix. (ie. it can still go wrong if we leave the field *blank*, but we can't assign the *wrong* kind of thing to it anymore)

# Answer
> 0 votes
Whoa, don't call GetComponent every frame in the Update loop, cache the component and use it.

```
using UnityEngine;
using System.Collections;

public class HealthHunger : MonoBehaviour {
    //public Transform HealthTarget; Not being used yet...
    public Transform HungerTarget;
    private Text _uiText;

void Start () {
    _uiText = HungerTarget.GetComponent<Text>();
}

void Update () {
    _uiText.text = "Whatever you want";
}
}

```

---
Tags: unity, gui
---


# Question
Title: How to normalize angles from points in java
**Previous thread on projectile slopes**

What is the velocity of a translating projectile in 2D?

**What I'm trying to do**

Get the slope at a constant speed for both X & Y Coordinates though I don't have an understanding on how to use Vectors in programming so I'm going off this guys equations but with both X & Y since I don't understand vectors. I can't tell at this point if there a direction or coordinate.

**What I've done so far**

Got everything ready

**What I need help with**

What do I have to put in as Syntax to normalize these 2 points even though their coordinates (Based off the answer on the given thread)

# Answer
> 0 votes
Here's the documentation on the type Vector2 in libGDX. https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Vector2.html

From this I can guess that code you could use would be something like this:

```
//Setup the positions of the player and the target position
Vector2 targetPos = new Vector2(Gdx.input.getX(), Gdx.input.getY());
Vector2 playerPos = new Vector2(Player.x, Player.y);

//Now create the vector from the player to the target
Vector2 toTargetVec = new Vector2(targetPos(targetPos.sub(playerPos)));
Vector2 directionalVec = new Vector2(toTargetVec.nor());

//Set the projectile's position
projectileX = Player.x;
projectileY = Player.y;

//Now we use this to start the projectile moving towards the target
projectileVX = directionalVec.x * projectileSpeed;
projectileVY = directionalVec.y * projectileSpeed;

```

I would highly recommend you learn how vectors work, they're used a lot in game programming.

PS. If you want to find the angle of the projectile, here's how:

```
projectileAngle = toTargetVec.angle();

```

---
Tags: java, libgdx, mathematics
---