# Question
Title: Moving towards and switching targets in Unity with collision
I have these nodes set up for a ship to move towards over time with out looking stops then repeats in a sequence.

like so:

1 2 3 1 2 3 1 2...

**THE PROBLEMS** i keep having either come from the inability to ***switch direction*** or the ship ***ignores all collision*** which i would like to be able to shoot it with actual objects.

**Ignores all Collision:**

```
Vector3 currentPosition = thisShip.transform.position;
    Vector3 directionOfTravel = targetPosition - currentPosition;
    directionOfTravel.Normalize();
    thisShip.MovePosition(currentPosition + directionOfTravel * speed * Time.smoothDeltaTime);

```

This one works perfectly but because MovePosition is a kin to translate and actually teleports objects it ignores all collision which i need.

**Can't Switch Direction:**

```
Vector3 currentPosition = thisShip.transform.position;
        Vector3 directionOfTravel = targetPosition - currentPosition;
        directionOfTravel.Normalize();
        thisShip.AddRelativeForce(currentPosition + directionOfTravel * speed * Time.smoothDeltaTime, ForceMode.Force);

```

so in this one i try to stop the rigid body by returning its velocity to zero and it does stop for a second but continues in its original direction anyways.

```
thisShip.velocity = Vector3.zero; // Use this to pause object

```

I believe i need another method of movement (*maybe use a CC*) or maybe i can make AddRelativeForce work and be able to switch targets like MovePosition does. I'd really like to get this one thing done so i can move on to other parts of the project.

# Answer
well i fixed it. lol well the reason it wasn't working right was because i used translate on another part of the script to move the whole ship on a rail while this part moves side to side. so these few line of code weren't the problem at all. guess that's what i get for trying to be secretive and hiding code. MovePosition works fine with collision. but still don't know what was going on with addrelativeforce. Meh well i solved it anyways now i can finally move on in development
> 0 votes

# Answer
**My apologies if I'm wrong** but.. Dude, drop that script and take a look at the tutorials, specially -Roll a Ball- and SpaceShooter

You're not checking for collisions you just posted the same code twice. The code for move your object have not sense: You're not applying forces or transforms. You're just adding and subtracting your current position to that mysterious targetPosition variable.

I'd never used MovePosition and yes I'm new in this so you're probably applying transformations, nevertheless, I'm pretty sure you don't know what you're doing. Am I right?

Remember that apply forces and transformation are not the same. Also I'm not sure if 'velocity' is deprecated and you should use the property from the component (rigidbody probably).

I guess you should drive your ship like a car but in the opposite way. Good luck, sorry I can't help but I can't wrote a comment
> 0 votes

---
Tags: unity, c#, collision-detection, movement, rigidbody
---


title: HTML/JS publish LibGDX

text:
# Question
Title: HTML/JS publish LibGDX
I want to publish an app created with libGDX (HTML/JS publishing). Here are the steps I am doing. **Right Click on the Project -\> Google -\> Gwt Compile -\> Compile.** After the compilation there is no .html file in the /war directory . There are 3 folders assets,html,WEB-INF . What am I doing wrong?

# Answer
On Android Studio, on the heeader menu go to: View-\>Tool Windows-\>Gradle

There you will see all you subprojects. open up the 'other', right click on the task 'dist' and click 'run'.

This will create the distribution file in your HTML-\>build-\>dist folder. You can copy those file to your root folder (or link your root folder to this location)
> -1 votes

---
Tags: libgdx, web, publishing
---


# Question
Title: Moving object to point a to point b smoothly
I am working on a problem where distance between the point A and B or given and object of interest should move smoothly from A to B.

I can control only control the speed of the object using this object should start slowly from point ease in and ease out at point B and need to exactly land on point B

I tried implementing ease in speed using distance covered however, at the beginning distance covered will be zero there will be *starting problem*. I solved starting problem using time elapsed as reference however this will not work precisely stoping object at point B, so I used distance remaining as a key to ease out.

This works for larger distance for smaller distance yet to tweak the code . Overall implementation messy not satisfied. Is there any generic solution to solve this problem? Note speed just a parameter controls overall movement of object, I can't say there is a exact relationship speed and distance covered.

(Unity developers: Note I am trying to control the movement of the character using three animation idle:speed=0, slowwalk:average speed=1, fastwalk: average speed=2)

# Answer
> 1 votes
If I understand your question correctly, you want to smoothly move an object from point A to point B.

I would use a coroutine:

```
private IEnumerator Move_Routine(Transform transform, Vector3 to, float speed)
{
    Vector3 from = transform.position;
    float distance = Vector3.Distance(from, to);
    float rate = speed / distance;

    for (float t = 0; t < 1; t += rate * Time.deltaTime)
    {
        transform.position = Vector3.Lerp(from, to, Mathf.SmoothStep(0f, 1f, t));
        yield return null;
    }

    // Ensure we end exactly at the destination,
    // since the loop can end a fraction away.
    transform.position = to;
}

```

And I would start it by calling:

```
StartCoroutine(Move_Routine(this.transform, Vector3.one, 1));

```

---
Tags: unity, movement, character
---


# Question
Title: How do I handle parallel lines when looking for intersections?
I'm using the following method to determine the intersection point of two vector2:

```
public static Vector2 LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2)
{
    // Get A,B,C of first line - points : startPoint1 to endPoint1
    float A1 = endPoint1.y - startPoint1.y;
    float B1 = startPoint1.x - endPoint1.x;
    float C1 = A1 * startPoint1.x + B1 * startPoint1.y;

    // Get A,B,C of second line - points : startPoint2 to endPoint2
    float A2 = endPoint2.y - startPoint2.y;
    float B2 = startPoint2.x - endPoint2.x;
    float C2 = A2 * startPoint2.x + B2 * startPoint2.y;

    // Check if the lines are parallel
    float delta = A1 * B2 - A2 * B1;
    if (delta == 0)
        throw new System.Exception("Lines are parallel");

    // Return the intersection point
    return new Vector2(
        (B2 * C1 - B1 * C2) / delta,
        (A1 * C2 - A2 * C1) / delta
    );
}

```

Currently the method throws an exception for parallel lines but I don't like the idea to wrap every call of that function in a try/catch.

Is there a better solution for this? I can't return null because Vector2 is a struct.

Maybe somthing like the following?

```
public static bool LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2, out Vector2 intersectionPoint)

```

# Answer
You can return a Nullable `Vector2?`

```
public static Vector2? LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1, Vector2 startPoint2, Vector2 endPoint2)
{
    // Get A,B,C of first line - points : startPoint1 to endPoint1
    float A1 = endPoint1.y - startPoint1.y;
    float B1 = startPoint1.x - endPoint1.x;
    float C1 = A1 * startPoint1.x + B1 * startPoint1.y;

    // Get A,B,C of second line - points : startPoint2 to endPoint2
    float A2 = endPoint2.y - startPoint2.y;
    float B2 = startPoint2.x - endPoint2.x;
    float C2 = A2 * startPoint2.x + B2 * startPoint2.y;

    // Check if the lines are parallel
    float delta = A1 * B2 - A2 * B1;
    if (delta == 0)
        return null;

    // Return the intersection point
    return new Vector2(
        (B2 * C1 - B1 * C2) / delta,
        (A1 * C2 - A2 * C1) / delta
    );
}

```

It lets you use a simple `if(intersectionPoint.HasValue)` instead of a try-catch at the call site.
> 3 votes

# Answer
I suggest changing your API so that it tells you explicitly whether the lines intersect:

```
public static bool LineIntersectionPoint(Vector2 startPoint1, Vector2 endPoint1,
                                         Vector2 startPoint2, Vector2 endPoint2,
                                         out Vector2 intersectionPoint)
{
    // ...

    if (delta == 0)
    {
        intersectionPoint = Vector2.zero;
        return false;
    }

    // Return the intersection point
    intersectionPoint = new Vector2(
        (B2 * C1 - B1 * C2) / delta,
        (A1 * C2 - A2 * C1) / delta
    );
    return true;
}

```

You can then use it like this:

```
if (LineIntersectionPoint(...., out intersectionPoint))
{
     // do something with intersectionPoint
}
else
{
     // possible fallback code
}

```

**Edit**: assign point to `zero` in the no-intersection case.
> 4 votes

---
Tags: unity, c#, vector, struct
---


# Question
Title: How to check the memory leackage in libGDX game development?
I'm developing a multi-platform game in libGDX. Sometimes there is a huge issue with memory. The game used to stick a lot. In fact, I even used pooling.

Is there any method to check the memory leakage in libGDX?

# Answer
> 2 votes
You can use a memory profiler like JProfiler(trial/paid) or JVmonitor(free) to take a snapshot of the heap when your program starts to eat up memory. These programs will at the very least tell you what type of object is eating up your memory. These of course will only work for the Desktop version of your app.

Also ensure that you are using pooling correctly. Specifically, the moment that you are done with an object created from a `Pool`, make sure you call `free()` on that object. Otherwise the next time you call `obtain()` the `Pool` will create a new object.

Also see if there is anywhere in your code that you are thrashing a pool. Meaning, if you call `obtain()` 1500 times in a row, then you will create 1500 objects. These objects will stay in memory until you clear the pool (depending on the `max` setting of the pool). You may want to redesign that part of the code so that you don't hit the pool so hard all at once.

Check out the Memory Management page of the libgdx wiki. It has a list of all the objects that must be disposed when you are done with them. If your game changes states/screens a lot, make sure that the resources you no longer need from a state gets disposed between states.

If you aren't already, make use of the AssetManager class. It uses reference counting so that everything you load can be shared between all users that need it. This is critical for large unmanaged objects like textures. This also means that once the reference count drops to 0, `AssetManager` will dispose of the asset for you.

---
Tags: libgdx
---


# Question
Title: What is the difference between Sprite and SpriteBatch, specifically in the context of libGDX?
I'm using libGDX and I'm confused about the difference between the Sprite and SpriteBatch.

Anybody can explain it to me in a simple way?

# Answer
A `Sprite` is simply a data structure that contains information on how and where to draw a texture (i.e. position, color, texture handle, rotation, scale).

Because of the way that OpenGL works, it is best to group or "batch" draw calls together to get the optimum performance. This grouping is why you will get an error if you try to draw to a `Batch` without first calling `batch.begin()` as this signals the Batch to start the work of grouping draw calls. When you call `draw()` on a batch, it isn't actually doing the work of drawing yet, it is only organizing the data you give it. It will wait to draw to the screen until `batch.end()` is called.

A `SpriteBatch` is a `Batch` which is used for drawing Sprites, more specifically, it deals with drawing a bunch of textures on Quads in OpenGL. In a `SpriteBatch` there is a lot of interaction behind the scenes with OpenGL that, thankfully, we don't have to do manually. There are a few parameters that `SpriteBatch` shares among all the sprites that are drawn to it, namely: projection and transformation matrices, tint color, shaders and blend settings.

You don't actually have to use the `Sprite` class to use a `SpriteBatch`. You can just give your own parameters to any of the draw calls that `SpriteBatch` provides. For convenience, the `Sprite` class has a `draw(Batch batch)` function that will forward all of the data in the `Sprite` to the approriate draw calls in the `Batch`
> 4 votes

# Answer
A Sprite is a single sprite, whereas a SpriteBatch is a collection of multiple sprites, all drawn using the same settings.
> -1 votes

---
Tags: libgdx
---


# Question
Title: How can I prevent P2P connections from leaking player IP addresses?
There's a common issue in multiplayer PC games like the older versions of Call of Duty where any connected player in a match can easily sniff the game packets and read the IP addresses of all the connected players. This is undesirable privacy-wise.

How can I reasonably protect players from malicious actors that may use their IP for nefarious purposes?

# Answer
> 2 votes
In any direct peer-to-peer game where one player is the host of the game server, you won't be able to hide players' IPs from the host nor protect the host from the players.

However, if you design your game with all players directly connecting to your hosted game servers and only allow packets in your game to be passed between the authoritative server and the players' clients there is no way in theory that any players would be able to discover an other's IP (unless you leak information through your game's protocol in some way, like broadcasting it with player lists or doing voice chat through a peer-to-peer plugin).

# Answer
> 1 votes
As Matt Jens Jensen already pointed out, there is no way to *always* protect your players privacy without hosting the servers yourself.

However, to accommodate more privacy-conscious players you could develop and offer a proxy server application for your game (client connects to proxy, proxy connects to host on their behalf and forwards all network messages). They can then install it on a server they trust, or you can offer to host instances of that tool yourself (which would of course only make sense if your server requires lots of CPU power but not that much bandwidth). This will increase latency but protect the users privacy. It can also be useful as a reverse proxy for players who want to host a server when behind a NAT or who don't want to reveal the real IP for the server. Such a tool is available for Half Life 1, for example.

# Answer
> 0 votes
Anonymity in P2P systems *is possible*—it's just hard, and too slow for most action games.

For example, the Tor network is serverless, and enforces anonymity by delivering all messages via intermediary peers, so that the receiver can't tell who originally sent them.

Such systems are of course much slower than a direct connection, but remain feasible for slower-paced genres such as turn-based strategy games.

---
Tags: client-server, security
---


title: Stream Output (SO) stage in Directx 12?

text:
# Question
Title: Stream Output (SO) stage in Directx 12?
Does Directx 12 have a Stream output Stage?

# Answer
> 2 votes
Yes, the documentation for setting the SO target can be found here. The pipeline chart shows you stream output in the pipeline (over there on the right):

Going forward, for many features, you can typically assume nearly the same functionality as DX11.

---
Tags: directx
---


title: SDD Inverse Kinematics with constraints

text:
# Question
Title: SDD Inverse Kinematics with constraints
I have a question regarding my quest on onderstanding IK solvers.

After viewing this movie on YouTube: https://www.youtube.com/watch?v=MvuO9ZHGr6k I started recreating it with JavaScript. Just 2d on canvas.

I have come to this point:

```
function IK(x, y, joints) {

    this.location = new Vector(x, y);

    // 0: Not visible
    // 1: Just bones
    // 2: Angle indicators
    this.drawLevel = 2;

    this.joints = joints;

    this.target   = new Vector(150, 420);
    this.active   = this.joints.length - 1;
    this.run      = true;
    this.slow     = true;
    this.oneByOne = true;
    this.attempts = 0;
}

IK.prototype.resetActive = function() {

    this.active = this.joints.length - 1;
};

IK.prototype.getAngles = function() {

    var activeToTargetAngle = Math.atan2(
        this.target.y - (this.anchors[this.active].y + this.location.y),
        this.target.x - (this.anchors[this.active].x + this.location.x)
    ) * (180 / Math.PI);

    var endToActiveAngle = this.joints[this.active].angle  * (180 / Math.PI);

    if (this.active !== (this.anchors.length - 1)) {

        endToActiveAngle = Math.atan2(
            (this.location.y + this.anchors[this.anchors.length - 1].y) -
            (this.location.y + this.anchors[this.active].y),
            (this.location.x + this.anchors[this.anchors.length - 1].x) -
            (this.location.x + this.anchors[this.active].x)
        ) * (180 / Math.PI);
    }

    return {
        activeToTarget: activeToTargetAngle,
        endToActive: endToActiveAngle
    };
};

IK.prototype.makeAnchors = function() {

    this.anchors = [];
    this.anchors.push(new Vector(0, 0));
    this.anchors.push(new Vector(
        this.anchors[0].x + Math.cos(this.joints[0].angle) * this.joints[0].length,
        this.anchors[0].y + Math.sin(this.joints[0].angle) * this.joints[0].length
    ));
    this.anchors.push(new Vector(
        this.anchors[1].x + Math.cos(this.joints[1].angle) * this.joints[1].length,
        this.anchors[1].y + Math.sin(this.joints[1].angle) * this.joints[1].length
    ));
    this.anchors.push(new Vector(
        this.anchors[2].x + Math.cos(this.joints[2].angle) * this.joints[2].length,
        this.anchors[2].y + Math.sin(this.joints[2].angle) * this.joints[2].length
    ));
    this.anchors.push(new Vector(
        this.anchors[3].x + Math.cos(this.joints[3].angle) * this.joints[3].length,
        this.anchors[3].y + Math.sin(this.joints[3].angle) * this.joints[3].length
    ));
};

IK.prototype.onTarget = function() {

    var endAffector = new Vector(
        this.location.x + this.anchors[this.anchors.length -1].x,
        this.location.y + this.anchors[this.anchors.length -1].y
    );

    var targetDifference = this.target.distance(endAffector);

    if (targetDifference < 3) {

        //console.log('On target, stopping!');
        return true;
    }

    return false;
};

IK.prototype.notResolvable = function() {

    if (this.attempts > 5000) {
        console.log('Not resolvable, stopping!');
        return true;
    }

    return false;
};

IK.prototype.shift = function() {

    this.active -= 1;
    if (this.active < 0) {
        this.resetActive();
    }
};

IK.prototype.step = function() {

    this.makeAnchors();

    var angle = this.getAngles();

    // The angle is different, rotate!
    if (angle.endToActive != angle.activeToTarget) {

        for (var j = this.active; j < this.joints.length; j++) {

            if (angle.endToActive < angle.activeToTarget) {

                this.joints[j].angle += 0.01;
            } else {

                this.joints[j].angle -= 0.01;
            }
        }

        // Done rotating towards
        if (this.oneByOne) {

            if (Math.floor(angle.endToActive) == Math.floor(angle.activeToTarget)) {

                this.shift();
            }
        } else {

            this.shift();
        }
    }

    // Continue?
    if (this.onTarget() || this.notResolvable()) {

        this.run = false;
    }

    this.attempts += 1;
};

IK.prototype.direct = function() {

    while (this.run) {

        this.step();
    }
};

IK.prototype.update = function() {

    if (this.run) {
        if (this.slow) {
            this.step();
        } else {
            this.direct();
        }
    }

    if (this.drawLevel > 0) {
        this.draw();
    }
};

IK.prototype.draw = function() {

    this.drawStart();
    this.drawBones();
    this.drawConstraints();
    this.drawAngleLines();
};

```

(I left out all the draw functions since make the example more convoluted than needed)

This IK object is initialized as follows:

```
var ik = new IK(centerX, centerY,
    [{
        angle: 3.5,
        length: 50,
        min: Math.PI + -0.2,
        max: Math.PI + 0.2
    }, {
        angle: 2.7,
        length: 100,
        min: -1,
        max: -.3
    }, {
        angle: 2.5,
        length: 100,
        min: -1,
        max: 0
    }, {
        angle: 2.5,
        length: 50,
        min: -0.5,
        max: 0.5
    }]
);

```

So far so good. This is working like I see in the example on YouTube but now I wan't to take it a step further by adding angle constraints and this is where I'm getting stuck.

In the joints object that I send to the constructor I added min and max values that are added or subtracted from the current joint angle. Defining a valid rotation range.

After that I added this function, to check if the angle is inside the defined min / max range:

IK.prototype.withinConstraints = function() {

```
if (this.joints[this.active - 1] !== undefined) {

    var min = (this.joints[this.active - 1].angle + this.joints[this.active].min) * (180 / Math.PI);
    var max = (this.joints[this.active - 1].angle + this.joints[this.active].max) * (180 / Math.PI);
    var angle = this.joints[this.active].angle * (180 / Math.PI);

    if (angle < min || angle > max) {

        this.shift();

        return false;
    }
}

```

}

I change the step function to:

```
IK.prototype.step = function() {

    this.makeAnchors();

    var angle = this.getAngles();

    // The angle is different, rotate!
    if (angle.endToActive != angle.activeToTarget) {

        for (var j = this.active; j < this.joints.length; j++) {

        this.joints[j].angle =

              // Constraints not exeeded?
              this.withinConstraints() ?

              // Move towards or from target
              (
                  angle.endToActive < angle.activeToTarget ?
                  this.joints[j].angle + 0.01 : this.joints[j].angle - 0.01
              )

              // Keep value
              : this.joints[j].angle;
        }

        // Done rotating towards
        if (this.oneByOne) {

            if (Math.floor(angle.endToActive) == Math.floor(angle.activeToTarget)) {

            this.shift();
        }
    } else {

        this.shift();
    }
}

// Continue?
if (this.onTarget() || this.notResolvable()) {

    this.run = false;
}

this.attempts += 1;
};

```

This is just one of many attempts to make it work but I realize I simply don't know how to go about it.

This makes the rotation get stuck on one of the max or min angles. After that it won't continue or try to reach the target by going in the opposite direction. (which is logical with the above code).

I think I'm missing logics here:

```
// Move towards or from target
(
    angle.endToActive < angle.activeToTarget ?
    this.joints[j].angle + 0.01 : this.joints[j].angle - 0.01
)

```

The angle.endToActive \< angle.activeToTarget is quite arbitrary.

Hopefully there is someone out there that can give me a push in the right direction.

---------- SOLUTION ---------

This is my solution for the constraints, if anyone might be interested.

I added the `dir()` function, this helps me find the desired rotation direction.

```
IK.prototype.dir = function(a, t) {

    var theta = t - a;

    if (theta < 0) {
        theta += 360;
    }

    if (theta > 180) {
        return false;
    }

    return true;
};

```

With that I changed the step function:

```
IK.prototype.step = function() {

    this.makeAnchors();

    var angle = this.getAngles();

    // The angle is different, rotate!
    if (angle.endToActive != angle.activeToTarget) {

        for (var j = this.active ; j < this.joints.length ; j++) {

            var min = 0;
            var max = 0;
            if (this.joints[j - 1] !== undefined) {
                min = this.joints[j - 1].angle + this.joints[j].min;
                max = this.joints[j - 1].angle + this.joints[j].max;
            } else {
                // Start joint
                min = this.joints[j].angle + this.joints[j].min;
                max = this.joints[j].angle + this.joints[j].max;
            }

            var a = 0;
            if (this.dir(angle.endToActive, angle.activeToTarget)) {
                a = this.joints[j].angle + 0.01;
            } else {
                a = this.joints[j].angle - 0.01;
            }

            if ((a > min && a < max)) {
                this.joints[j].angle = a;
            } else {
                this.shift();
            }
        }

        // Done rotating towards
        if (this.oneByOne) {

            if (Math.floor(angle.endToActive) == Math.floor(angle.activeToTarget)) {

                this.shift();
            }
        } else {

            this.shift();
        }
    }

    // Continue?
    if (this.onTarget() || this.notResolvable()) {

        this.run = false;
    }

    this.attempts += 1;
};

```

Now I have to optimize this script, I feel it's using more processor power than needed. But that's the next phase.

# Answer
The gist of CCD is really nothing dazzling. Here's the description of a serial set-up (a chain of links and joints)

* you have an assembly of N joints and N links
* the first joint is called the root joint and has index 0
* joint `i` defines the frame where the rigid body for link `i` has its geometry described in (it's easier since people usually select a local frame axis to be aligned with a link)
* joint `N-1` defines a special link, with index `N-1` called an *end effector*

**Assumptions**:

* each joint `i` has an angular parameter that allows it to behave like a hinge that connects links `i-1` and `i` (except for the root joint that controls the rotation of the entire chain with respect to a so-called world-frame of reference)
* each joint angle, denoted by `theta_i` is constrained in a subrange of \[-2pi;2pi\], bounded by `theta_min_i` and `theta_max_i`

The ***heart*** of the CCD algorithm is a concept akin to how a Gaussian relaxation solver proceeds:

* it iterates through all joints and for each joint `i` it tries to find the best angle `theta_target_i` that minimizes the distance (and orientation difference if you need that too) between the current position of the end effector and the goal position where you want the effector to reach
* when the optimal `theta_target_i` is found, it is clamped to the `theta_min_i` and `theta_max_i` interval (see numerical clamping)
* when joint `i+1` is considered in the next iteration, the already modified kinematic chain (using the adjusted `theta_target_i`) will have moved closer to the target. Now joint `i+1` needs to move it even further towards the goal position
* the iterative process can be executed in batches: you repeat the whole process going from `i=0` to `i=N-1` either `K` times or until your are satisfied with the distance error.

The answer to your question is that you should just perform the clamping and probably increase `K` (experimentally determinable) - see reference  in the Bibliography below.

**Bibliography**:

1. https://www.thinkmind.org/download.php?articleid=content\_2012\_4\_10\_60013
2. http://ttic.uchicago.edu/~tewari/research/saha10finite.pdf
3. http://digital.liby.waikato.ac.nz/conferences/ivcnz07/papers/ivcnz07-paper34.pdf
> 1 votes

---
Tags: javascript, animation, html-canvas, skeletal-animation, inverse-kinematics
---


title: Tetris implementing rotation

text:
# Question
Title: Tetris implementing rotation
I am currently at the last stage of the Tetris Clone using SDL library, the only thing left is rotation. For each piece I have a separate class, and in order to move the pieces down I use a method:

```
void PieceZ::movePieceDown()
{
  drawBlock(x1,y1++);
  drawBlock(x2,y3++);
  drawBlock(x3,y3++);
  drawBlock(x4,y4++);
}

```

This method is called like that: `current->movePieceDown();` where `current` represents a pointer to the current piece. Now to rotate the piece I have another method:

```
void PieceZ::rotatePiece()
{
  drawBlock(newX1,newY2++);
  drawBlock(x2,y2);
  drawBlock(newX3,newY3++);
  drawBlock(newX4,newY4++);
}

```

New X and Y coordinates are calculated elsewhere, with x2 and y2 taken as the origin. My question is how do I swap `current->movePieceDown()` with `current->rotatePiece()` while the piece is moving? Taking into acount that I am handling keyboard events in another method.

# Answer
> 0 votes
I found a solution, I am posting it just in case. Basically I removed the method `rotatePiece()`, instead of that I have a method that calculates the rotation independently of drawing:

```
void PieceZ::getRotation()
{
  newX1 = (y1-y2) + x2;
  newY1 = (x2-x1) + y2;

  newX3 = (y3-y2) + x2;
  newY3 = (x2-x3) + y2;

  newX4 = (y4-y2) + x2;
  newY4 = (x2-x4) + y2;

  x1 = newX1;
  x3 = newX3;
  x4 = newX4;

  y1 = newY1;
  y3 = newY3;
  y4 = newY4;
}

```

`new` values are set to 0 initially, and every time a user presses a button on the keyboard this method gets called, it calculates the new rotation in `new` and assigns it to `x` and `y` values. Which gives you a 90 degree counter clockwise rotation.

# Answer
> 0 votes
Alternatively, you could store four different pre-defined rotations and swap amongst them.

---
Tags: c++, objective-c
---


title: Make a door in a cube-wall

text:
# Question
Title: Make a door in a cube-wall
I have created a wall using a cube in Unity. Now I want to create a door in it.

How can I make a door in that cube?

Consider that the cube is automatically generated, so i have to generate the door in a C# script.

# Answer
Unity primitives are not like actual 3D models, they are great for concepts but do not afford much versatility. I recommend that you start with changing your original wall prefab.

* Create an empty game object and in it make 3 cubes.
* Next, arrange the cubes to look like a wall with a space for the door.
* Make a prefab of this object, maybe name it "wall"

Now make a new cube and size it to fit the hole in the wall. Keep an eye on the transform position in the upper right-hand corner.

You should probably make a prefab of the door object as well.

In C# you'll want to create a "public transform door" this will be visible in the inspector. You can then Instantiate the door at the position you need the door to be. That should look something like:

Instantiate (door, door.position, Quaternion.identity);

In the unity inspector you'll want to drag and drop the door prefab in slot that appears as the door transform.

Hope that helps!
> 1 votes

---
Tags: unity
---


# Question
Title: How can I carry around an inventory in my inventory?
I'm working on a mod for soul gems in Skyrim and want to add something like a Bag of Holding from souls.

The most simplyfied strategy I can come up with is

1. Create an invisible Black Soul Gem to catch a trapped soul in inventory
2. Create an item to act as representation of the soul wallet in inventory
3. Create an invisible container somewhere to store the souls and link it to the above
4. Create a script that detects soul trap and transfers it from inventory to soul wallet as a real black soul gem (or whatever is needed).

Ideally I'd want to make this a little more balanced that just handing out soul gems like candy but I think I could do that on my own once I actually get this far.

So this is about **both** parts (now):

1. **How can I carry around an inventory within my inventory?**
2. **How can I detect that a soul has been captured** (in my invisible gem)?

# Answer
Let's go through this step by step.

Before you can do anything else, you need to prevent the game from filling a normal empty soul gem which the player might be carrying in open inventory. The most thorough way to do this is to remove the normal soul trap magic effect from the soul trap spell and enchantment, and replace it with your own. Alternatively, you can use inventory events to detect when the player picks up a soul gem and remove it from their inventory, but this is likely to interfere with player freedom ("Why does this mod keep stealing my soul gems?"). An invisible black soul gem *will not work*, for several reasons, most importantly because there's no way to force the game to select that gem. If the player is carrying other black soul gems, a smaller gem that's big enough to hold the soul in question, or Azura's Star, you cannot prevent the game from selecting the "wrong" gem.

Assuming you choose to remove the standard magic effect, you will want to create your own custom effect, by copying the existing effect and removing its script(s) and (perhaps) keyword(s). This should have an ActiveMagicEffect script on it to detect when the affected actor dies. Since ActiveMagicEffect also receives events from the actor, it's a simple matter to write an OnDeath event to detect the victim's death and add a filled soul gem of the appropriate size.

But we don't just want to put the gems in the player's inventory. We want to stuff them into a bag of holding. So you create a cell with a container (e.g. a chest), as sarahm suggests in a comment, set it not to respawn, and put your soul gems there. When you need to open the bag of holding, you can activate the container or just use Papyrus to move items between it and open inventory. The latter may be preferable if you want to prevent the player from putting random objects into the bag.

It would be nice to also have the soul trap special effect play when the victim dies, but I'm not entirely sure how to do this.
> 2 votes

---
Tags: modding, steam, skyrim-modding
---


title: DirectX 11 Vertex Shader Fragmentation

text:
# Question
Title: DirectX 11 Vertex Shader Fragmentation
I was wondering how my vertex shader is causing my cube to be render weirdly? I am using the Visual Studio graphics tool and see that my input assembler is correctly receiving the cube and I can only guess my issue is within my shader. I did enable device creation flags but nothing related to the issue.

```
//Constant Buffer Variables
cbuffer constantObjects : register (b0)
{
    matrix World;
    matrix View;
    matrix Projection;
}

// Input Structure
struct VS_INPUT
{
    float3 inputPosition : POSITION0;
    float4 inputColor: COLOR0;
};

// Output Structure
struct VS_OUTPUT
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VS_OUTPUT VS(VS_INPUT input)
{
    // Create Pixel Shader output
    VS_OUTPUT output;

    float4 pos = float4(input.inputPosition, 1.0f);

    // Multiple to get worldViewProject for object position
    output.position = mul(pos, World);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);

    // Simply set color to color;
    output.color = input.inputColor;

    // Return position and color to PS
    return output;
}

// Create World View
worldMatrix = DirectX::XMMatrixIdentity();

// Create view matrix
DirectX::XMVECTOR eyePosition = DirectX::XMVectorSet(0.0f, 1.0f, -5.0f, 0.0f);
DirectX::XMVECTOR targetPosition = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
DirectX::XMVECTOR upDirection = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

// Store View Matrix
viewMatrix = DirectX::XMMatrixLookAtLH(eyePosition, targetPosition, upDirection);

// Create Projection Matrix
projectionMatrix = DirectX::XMMatrixPerspectiveFovLH(DirectX::XM_PIDIV2, (float)getHeight(), 0.01f, 100.0f);

```

It might be an issue with my world, view, and projection matrix but I don't really understand why that might be the issue. Here is the debug information. As you can see it goes to the input assembler correctly and has an issue with the vertex shader. Any help will be appreciated.

# Answer
> 1 votes
Fixed!!!!! Forgot to transpose world, view, and projection matrix. So fixing the aspect ratio and making sure to transpose the matrices fixed the issue. I have to remember that HLSL is column-major rather than row major.

---
Tags: directx, graphics, vertex
---


# Question
Title: How can I get the assignment of an object back?
I have been struggling with this NullReferenceExpection error.

When I don't add anything and just use this version of the code. The game adds a tower, upgrades a tower and takes money for it.

It worked all fine until I tried to add a menu that opens up and then you can choose a tower type you can buy.

So after I add all of this I get a `NullReferenceExpection` at `return tower == null && gameManager.Gold >= cost;` and at `gameManager.Gold -= tower.GetComponent<TowerData>().CurrentLevel.cost;`. The game also doesn't take any money from purchases and you can spawn near infinite amounts of towers on one spot.

> //tower = (GameObject)
>
> theTowerMenu.gameObject.SetActive (false);
>
> transform.position = new Vector3(openSpot.transform.position.x, openSpot.transform.position.y, transform.position.z

If i take 'tower = (GameObject)' out of comments I get "error CS0030: Cannot convert type `void' to`UnityEngine.GameObject'".

The current script:

```
using UnityEngine;
using System.Collections;

public class PlaceTower : MonoBehaviour {

public GameObject towerPrefab;
private GameObject tower;

public GameObject openSpot;

private GameManagerBehavior gameManager;

public GameObject theTowerMenu;

// Use this for initialization
void Start () {
    gameManager = GameObject.Find ("GameManager").GetComponent<GameManagerBehavior>();
}

// Update is called once per frame
void Update () {

}

private bool canPlaceTower() {
    int cost = towerPrefab.GetComponent<TowerData> ().levels[0].cost;
    return tower == null && gameManager.Gold >= cost;
}

void OnMouseUp () {
    if (canPlaceTower ()) {
        //tower = (GameObject)
        theTowerMenu.gameObject.SetActive (false);
        transform.position = new Vector3(openSpot.transform.position.x, openSpot.transform.position.y, transform.position.z);
        Instantiate (towerPrefab, transform.position, Quaternion.identity);

        AudioSource audioSource = gameObject.GetComponent<AudioSource> ();
        audioSource.PlayOneShot (audioSource.clip);

        gameManager.Gold -= tower.GetComponent<TowerData>().CurrentLevel.cost;
    } else if (canUpgradeTower ()) {
        tower.GetComponent<TowerData> ().increaseLevel ();
        AudioSource audioSource = gameObject.GetComponent<AudioSource> ();
        audioSource.PlayOneShot (audioSource.clip);
        gameManager.Gold -= tower.GetComponent<TowerData> ().CurrentLevel.cost;
    }

}

private bool canUpgradeTower() {
    if (tower != null) {
        TowerData towerData = tower.GetComponent<TowerData> ();
        TowerLevel nextLevel = towerData.getNextLevel ();
        if (nextLevel != null) {
            return gameManager.Gold >= nextLevel.cost;
        }
    }
    return false;
}
}

```

Please help. I've been stuck with this for a long time.

# Answer
> 3 votes
You are creating a tower prefab with `Instantiate (towerPrefab, transform.position, Quaternion.identity);`, but you don't do anything with the GameObject it returns. The result is that your newly created tower is just an independent GameObject in your scene with no relation at all to your `PlaceTower` game object which created it.

It *seems* like you want the newly created tower assigned to the `private GameObject tower;` variable so you can reference it at a later point in the script:

```
tower = Instantiate (towerPrefab, transform.position, Quaternion.identity) as GameObject;

```

You might also want to make the tower a child-object of the PlaceTower object by adding the line `tower.transform.SetParent(transform)` below the previous one.

# Answer
> 2 votes
With your current logic you have no choice but to run into a null reference exception.
You never assign anything to `tower`. The check canPlaceTower is only returning true if `tower` is `null` but in the code of the if statement you use tower: `tower.GetComponent<TowerData>().CurrentLevel.cost;`.
That can't work. If you want to create a new tower instance you have to create from one a prefab or something else. One option would be to do it like this:

```
//instead of this:
//tower = (GameObject)
//use this:
tower = MonoBehaviour.Instantiate(Resources.Load("Path/To/towerPrefab")) as GameObject;
//Set position and rotation next.

```

There are other options like using the existing `towerPrefab`:

```
tower = (GameObject)Instantiate(towerPrefab, transform.position, Quaternion.identity);

```

Which looks like what you are looking for according to your line `Instantiate (towerPrefab, transform.position, Quaternion.identity);`where you miss the assignment to `tower`.

---
Tags: c#, unity, scripting
---


# Question
Title: Quill18 Tutorial broken or Have I broken something?
Busy following a Quill18 Tutorial for a Tower defence game and It keeps giving me an error(NullReferenceException: Object reference not set to an instance of an object Solution 'TowerDefence') Now I have even downloaded his code and I have mine exactly the same. So either Its the newer version of Unity that is causing the issue or I'm missing something.

I would appreciate it if someone could help me find the missing link here. Thank you

I have attached the code below

```
public class Turret : MonoBehaviour {

public Transform turretTransform;

// Use this for initialization
void Start()
{
    turretTransform = turretTransform.Find("Turret");
}
    // Update is called once per frame
    void Update()
{//TODO: Optimize this!
        Enemy[] enemies = GameObject.FindObjectsOfType<Enemy>();

        Enemy nearestEnemy = null;
        float dist = Mathf.Infinity;
        foreach (Enemy e in enemies)
        {
            float d = Vector3.Distance(this.transform.position, e.transform.position);
            if (nearestEnemy == null || d < dist)
            {
                nearestEnemy = e;
                dist = d;
            }
        }
        if (nearestEnemy == null)
        {
            Debug.Log("No Enemies");
            return;
        }
        Vector3 dir = nearestEnemy.transform.position - this.transform.position;

        Quaternion lookrot = Quaternion.LookRotation(dir);

        //Debug.Log(lookrot.eulerAngles.y);

        turretTransform.transform.rotation = Quaternion.Euler(0, lookrot.eulerAngles.y, 0);
    }
}

```

# Answer
Ok, I figured it out! I needed to make sure that when it found "turret" it needed to look for the transform.

```
void Start()
{
    turretTransform = turretTransform.Find("Turret").transform;
}

```
> 1 votes

---
Tags: c#, game-design, unity
---


# Question
Title: How to constraint random spawn points to a road?
I have a terrain and a road.

I would like for spawn points to randomly appear on the road, and not outside on the terrain.

How to assign the spawn points to only be between the road and in random positions on the road?

# Answer
I would create a box and spawn object inside it. Or if your road is windy you can use multiple boxes or some other shape. Here is some code:

```
using UnityEngine;
using System.Collections;

/// <summary>
/// Spawns a prefab randomly throughout the volume of a Unity transform. Attach to a Unity cube to visually scale or rotate. For best results disable collider and renderer.
/// </summary>
public class SpawningArea : MonoBehaviour {

public GameObject ObjectToSpawn;
public float RateOfSpawn = 1;

private float nextSpawn = 0;

    // Update is called once per frame
    void Update () {

        if(Time.time > nextSpawn)
        {
            nextSpawn = Time.time + RateOfSpawn;

            // Random position within this transform
            Vector3 rndPosWithin;
            rndPosWithin = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
            rndPosWithin = transform.TransformPoint(rndPosWithin * .5f);
            Instantiate(ObjectToSpawn, rndPosWithin, transform.rotation);
        }
    }
}

```
> 1 votes

---
Tags: unity, algorithm
---


# Question
Title: How do I center a sky sphere on the camera?
I'm trying to render a sky using D3D 11. What I have seen in tutorials so far uses cube mapping, which I don't want to use. I want to create a sphere, texture it, and center that sphere on the camera, but I don't know how to do the last part.

How do I center it around the camera?

# Answer
Set the sphere's world space position equal to the camera's world space position. Or set the sphere's view space position to the zero vector.
> 1 votes

---
Tags: skybox
---


# Question
Title: Physics2D raycasting with a perspective camera and tilted sprites
So i ran into this problem today. I want to have a perspective camera and sprites that are rotated by lets say 1.5 on the X axis. The problem is that the 2D raycast does not work correctly, it returns the wrong colliders. Here is the implementation:

```
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.up);
            if(hit.collider)
            {
                Debug.Log(hit.collider.gameObject.name);
            }

```

Now if my camera is orthographic everything works great. How can I make it work with a perspective camera? Should I use 3d colliders and raycasts ?

# Answer
> 1 votes
Have you considered using the EventSystem instead of raycasting yourself?

In a nutshell:

1. Add a "Physics2DRaycaster" componenent to your camera
2. Add a 2D collider to your GameObject
3. Create a class that implements UnityEngine.EventSystems.IPointerClickHandler, and place it on your object with the collider.

You will find that the EventSystem can be enormously useful, it has a decent array of interfaces beyond the one listed above.

Check out this great little video for more if you are interested, it contains some examples of how to use the EventSystem for various things like making sure your clicking on an object and not part of the UI, how to replace OnMouseDown, etc.

---
Tags: unity, c#
---


# Question
Title: LWJGL: Camera distance from image plane?
Let me paste some code before I ask the question...

```
public static void createWindow(int[] args) {

    try {

        Display.setFullscreen(false);
        DisplayMode d[] = Display.getAvailableDisplayModes();
        for (int i = 0; i < d.length; i++) {
            if (d[i].getWidth() == args[0] && d[i].getHeight() == args[1]
                    && d[i].getBitsPerPixel() == 32) {
                displayMode = d[i];
                break;
            }
        }

        Display.setDisplayMode(displayMode);
        Display.create();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }

}

public static void initGL() {
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    GL11.glShadeModel(GL11.GL_SMOOTH);
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL11.glClearDepth(1.0);
    GL11.glEnable(GL11.GL_DEPTH_TEST);
    GL11.glDepthFunc(GL11.GL_LEQUAL);

    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();

    GLU.gluPerspective(45.0f, (float) displayMode.getWidth()
            / (float) displayMode.getHeight(), 0.1f, 100.0f);

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
}

```

So, with the camera and screen setup out of the way, I can now ask the actual question: How do I know what the camera distance is from the image plane? I also would like to know what the angle between the image plane's center normal and a line drawn from the middle of one of the edges to the camera position is.

This will be used to consequently draw a vector from the camera's position through the player's click-coordinates to determine the world coordinates they clicked (or could've clicked).

Also, when I set the camera coordinates, do I set the coordinates of the camera or do I set the coordinates of the image plane?

Thank you for your help.

EDIT: So, I managed to solve how to calculate the distance of the camera... Here's the relevant code...

```
private static float getScreenFOV(int dim) {
    if (dim == 0) {
        float dist = (float) Math.tan((Math.PI / 2 - Math.toRadians(FOV_Y))/2) * 0.5f;
        float FOV_X = 2 * (float) Math.atan(getScreenRatio() * 0.5f / dist);
        return FOV_X;
    } else if (dim == 1) {
        return FOV_Y;
    }
    return 0;
}

```

FOV\_Y is the Field of View that one defines in gluPerspective (float fovy in javadoc). This seems to be (and would logically be) for the height of the screen. Now I just need to figure out how to calculate that vector.

# Answer
> How do I know what the camera distance is from the image plane?

I'm not sure if this is a meaningful question to ask - what is the image plane? A real camera has a plane on which an image is formed, but in OpenGL there is no such thing. If you need this for some physics-based calculation, you could possibly use the near clipping plane distance (third argument to gluPerspective, here it's 0.1 units).

> I also would like to know what the angle between the image plane's center normal and a line drawn from the middle of one of the edges to the camera position is.

The angle between the top and bottom edges of the frustum is the "fovy" parameter you passed to Javadoc, so the angle between the top and the normal will be half that.

Since the image isn't square, the horizontal angle will be different from this; you could use some trigonometry to calculate it. If your screen width and height in pixels is `sw` and `sh`, your near plane distance is `npd`, and your vertical FOV is `fovy`, then:

* The height of the near plane in view is `sh` pixels, and `npd*tan(fovy/2)*2` OpenGL units.
* Each pixel must be `npd*tan(fovy/2)*2/sh` OpenGL units.
* The width of the near plane in view is `sw` pixels, at the same scale, so `npd*tan(fovy/2)*2*sw/sh` OpenGL units.
* The horizontal FOV is `atan(width / npd / 2)*2` or `atan(npd*tan(fovy/2)*2*sw/sh/npd/2)*2`
* Simplifying: `atan(tan(fovy/2)*sw/sh)*2`

That's assuming I didn't make any math mistakes there.

Like before, the angle between the normal and one of the edges will be half the FOV, so remove the `*2` at the end to calculate that instead.

> Also, when I set the camera coordinates, do I set the coordinates of the camera or do I set the coordinates of the image plane?

OpenGL has no concept of "camera coordinates". If you have a camera in your program, it's a completely made-up concept, and what you're actually doing is moving the entire world the opposite way.
> 0 votes

# Answer
To answer your question about *moving the camera*, this is what I do at the start of each frame of my program:

```
/**
 * Looks through the camera, effectively updating how we view the game.
 *
 * @param updateFrustum recalculates the frustum if true
 */
public void lookThrough(boolean updateFrustum) {
    glRotatef(rx, 1.0f, 0.0f, 0.0f);
    glRotatef(ry, 0.0f, 1.0f, 0.0f);
    glRotatef(rz, 0.0f, 0.0f, 1.0f);
    glTranslatef(position.x, position.y, position.z);
    if (updateFrustum) {
        frustum.calculateFrustum();
        }
    }
}

```

This is called **after** I handle the inputs from keyboard and mouse, which probably called the `move()` method (or `pitch()` or `roll()` or `yaw()`, which are equivalent):

```
/**
 * Moves the camera a specific amount in a specific direction.
 *
 * @param amount
 * @param dir
 */
public void move(float amount, Camera.Direction direction) {
    switch (direction) {
    case BACKWARDS_OR_FORWARDS:
        position.z += amount * Math.sin(Math.toRadians(ry + 90));
        position.x += amount * Math.cos(Math.toRadians(ry + 90));
        position.y += amount * Math.sin(Math.toRadians(rx));
        break;
    case SIDEWAYS:
        position.z += amount * Math.sin(Math.toRadians(ry));
        position.x += amount * Math.cos(Math.toRadians(ry));
        break;
    case UP_OR_DOWN:
        // TODO: implement
    default:
        break;
    }
}

```

I hope the code is self-sufficient to see what I mean but the most important of course are the `glRotatef` and `glTranslatef` commands, which moves the point and direction from where I draw my content each frame.

To answer your second question:

When you want to know where your mouse pointer crosses a plane (the terrain for example), you would need to create a line (or vector) from the position of the camera (you have the position and angle of the camera, so you can create a vector out of that) towards the terrain and calculate the point of intersection.
> 1 votes

---
Tags: java, camera, lwjgl, input, mouse
---


# Question
Title: Question regarding simplification of world creation and collision (VISUAL BASIC)
In my computer programming class we are creating our own top down adventure games in Visual Basic. Currently I have been able to have the player appear on screen and collide with a block on the screen.

My question comes from the collision code which is here:

```
Public Sub checkCollide()
        'If player's top is in range of the block above it...
        If yPos = Form1.block1Y + 49 And (xPos >= Form1.block1X And xPos <= Form1.block1X + 49 Or xPos + 49 <= Form1.block1X + 49 And xPos + 49 >= Form1.block1X) Then
            'Disable upward movement
            canMoveUp = False

        Else
            canMoveUp = True
        End If

        'If player's left is in range of the block to its left...
        If xPos = Form1.block1X + 49 And (yPos >= Form1.block1Y And yPos <= Form1.block1Y + 49 Or yPos + 49 <= Form1.block1Y + 49 And yPos + 49 >= Form1.block1Y) Then
            'Disable left movement
            canMoveLeft = False

        Else
            canMoveLeft = True
        End If

        'If the player's underside is in range of the block below it...
        If yPos + 24 = Form1.block1Y And (xPos >= Form1.block1X And xPos <= Form1.block1X + 49 Or xPos + 49 <= Form1.block1X + 49 And xPos + 49 >= Form1.block1X) Then
            'Disable downward movement
            canMoveDown = False

        Else
            canMoveDown = True
        End If

        'If the player's right is in range of the block to the right of it...
        If xPos + 24 = Form1.block1X And (yPos >= Form1.block1Y And yPos <= Form1.block1Y + 49 Or yPos + 49 <= Form1.block1Y + 49 And yPos + 49 >= Form1.block1Y) Then
            canMoveRight = False

        Else
            canMoveRight = True
        End If
End Sub

```

I was wondering if there was a way to create a struct or class of some sort that allowed for a much simpler way to do this. Each block is a picture box. When creating a new block I need to repeat these steps for each one created, resulting in a huge list that is probably unnecessary. Thanks.

# Answer
> 0 votes
Have you considered making an array of those PictureBox-es? But, to set the array one by one to an existing object is a pain for sure. You might want to initialize those objects by code. This might help

If you see in those example codes:

```
Dim x(10) As widget
// x now contains 11 elements of type widget, x(0) through x(10).

```

That is how you initialize an array.

```
// Assign a reference to an existing object to two array elements.

x(0) = specialWidget
x(1) = specialWidget

```

That is how you set an array one by one to an existing object. Pain (At least from my experience, i have to set 65 objects one by one).

```
// Create each element of an array by using a loop.
For q As Integer = 0 To 10
    x(q) = New widget()
Next q

```

And that is how you can by a way set the array with a new objects. You can set the position and everything else (initializing, like the position, width, and height of the objects) normally.

Also, there's this thread too about using `List(Of T)`. It seems that it doesn't have to set the size of the array, so it should be more dynamic.

---

Oh, and for the collision check. You can do it like this pseudocode:

```
For i As Integer = 0 To x.Length
    // Check collision, to access the array use x(i)
Next

```

\*I hope i get that right from here

---
Tags: collision-detection, visual-basic
---


title: How to jump in Box2D with LibGDX

text:
# Question
Title: How to jump in Box2D with LibGDX
I am making a 2D platformer in LibGDX with both Ashley and Box2D.

I have it so, that the `PlayerControllerSystem` watches for the jump key being pressed:

```
// Jumping
if (Gdx.input.isKeyPressed(Keybindings.KEY_JUMP)) {
    entity.add(new JumpingComponent());
}

```

This works like a charm. Every time I press the jump key the `PlayerJumpingSystem` fires up:

```
/**
* System used for the player jumping mechanism
* @author Tim
*/
public class PlayerJumpingSystem extends IteratingSystem {

    @SuppressWarnings("unused")
    private final static String TAG = PlayerJumpingSystem.class.getName();

    // Variable declaration
    @SuppressWarnings("unchecked")
    private static final Family family = Family.all(
            PositionComponent.class,
            VelocityComponent.class,
            PhysicsComponent.class,
            PlayerComponent.class,
            JumpingComponent.class).get();

    public PlayerJumpingSystem () {
        super(family);
    }

    @Override
    protected void processEntity (Entity entity, float deltaTime) {
        PositionComponent position = Mappers.position.get(entity);
        VelocityComponent velocity = Mappers.velocity.get(entity);
        PhysicsComponent physics = Mappers.physics.get(entity);

        if (velocity.y > 0) {
            // We are ascending
            physics.body.applyLinearImpulse(0, -Constants.JUMP_FORCE, position.x, position.y, true);
        }

        if (velocity.y < 0) {
            // We are descending
            physics.body.applyLinearImpulse(0, Constants.JUMP_FORCE, position.x, position.y, true);
        }

        else if (velocity.y == 0) {
            entity.remove(JumpingComponent.class);
            Gdx.app.log(TAG, "JumpingComponent removed");
        }
    }

}

```

It gives very weird jumping behaviour. Does anyone know how to implement jumping with Box2D in a good way? Thanks in advance!

# Answer
you can do like this:

# In your hud class

```
public jumpButtonPressed = false;
buttonJump.addListener(new InputListener() {
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        jumpButtonPressed = true;
        return true;
    }
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        jumpButtonPressed = false;
    }
});

```

# In controll buttons

```
public void updateInput(float dt) {
    if ((Gdx.input.isKeyJustPressed(Input.Keys.UP) || Gdx.input.isKeyJustPressed(Input.Keys.W)) || hud.jumpButtonPressed == true) {
        hud.jumpButtonPressed = false;
        if (player.getState() != player.State.JUMPING) {

            player.b2body.setLinearVelocity(player.b2body.getLinearVelocity().x,0);
            player.b2body.applyForceToCenter(0, 160f, true);

        }
    }
}

```

# In player class

```
public State getState(){

if(b2body.getLinearVelocity().y >0 || (b2body.getLinearVelocity().y < 0 && estadoAnterior == State.JUMPING))
    return State.JUMPING;
else if(b2body.getLinearVelocity().y<0)
    return State.FALLING;
else
    return State.STOPSTATE;
}

```

in my case, if the player is falling and press jump button he will jump, but you can create more states like you want
> 1 votes

---
Tags: java, libgdx, jumping
---


title: Read values from text file

text:
# Question
Title: Read values from text file
I'm trying to read the data from a text file with numbers separated by tab. And store those numbers in a list of float for example. So that I can then use that list on runtime. Any easy way of doing this?

# Answer
If the text file in question is present at compile time, then in Unity I'd recommend including it in your Assets folder as a TextAsset. That makes Unity do the work of managing the file, and gives us simple access to the data inside. :)

Anything with one of these extensions is automatically imported as a TextAsset, though you can customize this:

```
.txt   .html   .htm    .xml    .bytes    .json    .csv    .yaml    .fnt

```

Now you can assign this asset to a script's `public TextAsset myTextAsset;` field, or load it dynamically at runtime with Resources.Load() just like working with other Unity assets you might be familiar with.

Then, when a script needs to convert this to a list of numbers, you can do...

```
// Split the text into an array of strings, cutting wherever there's a tab.
string[] numberStrings = myTextAsset.text.split('\t');

// Prepare a float array of the same size.
float[]  numbers = new float(numberStrings.length);
for(int i = 0; i < numberStrings.length; i++)
   numbers[i] = float.Parse(nuberStrings[i];

```

The above will also work for a local file selected by the user at runtime, or one downloaded from a server, though in that case you'll likely be getting the text from a WWW object instead of a TextAsset, but they both have a `text` property containing the text contents of the file so it's very similar.
> 1 votes

# Answer
```
using (StreamReader file = new StreamReader(@"C:\Where the file is.txt"))
{
    while ((line = file.ReadLine()) != null)
    {

        char[] delimiters = new char[] { '\t' };
        string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < parts.Length; i++)
        {
            Debug.Log(parts[i]);
        }

    }

    file.Close();
}

```

This piece of code opens up a file, reads all its lines and uses the Split method with the correct delimeiter(requested by OP). StringSplitOptions is used to tell the Split method to ignore empty spaces within the splits. Then I use a simple for loop to log each element of the array to the unity console and of course close the file after we are done using it(cause I'm just nice like that)
> 1 votes

---
Tags: unity, importing
---


title: LibGDX - Shader not being applied

text:
# Question
Title: LibGDX - Shader not being applied
I've recently encountered a strange problem with my program and I can't seem to fix it. When I try to apply a shader to my `SpriteBatch` it doesn't change. I've debugged this problem like so:

```
if (test) {
    System.out.println("Batch shader: " + stage.getBatch().getShader());
    System.out.println("Default shader: " + Assets.getDefaultShader());
    System.out.println("Default batch: " + Assets.SPRITE_BATCH);
    System.out.println("Stage batch: " + stage.getBatch());
}

stage.getBatch().setShader(null);
if (test)
    System.out.println("Batch shader: " + stage.getBatch().getShader()); //Should print null
stage.act();
if (test)
    System.out.println("Batch shader: " + stage.getBatch().getShader());
stage.draw();
if (test)
    System.out.println("Batch shader: " + stage.getBatch().getShader());
test = false;

```

All of those shaders print the exact same thing, and the batches are also the same (the batches are supposed to be the same). Any ideas why?

# Answer
After sitting with this problem for hours I finally found out what was wrong.

If you set the shader to `null` on your `SpriteBatch`, it uses the default shader provided to the `SpriteBatch`. For me, the default shader was `Assets.getDefaultShader()`, so when I set the shader to null it just used that shader. I fixed this by simply not settings a default shader to the `SpriteBatch`.
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: Libgdx - changing tiledmap smoothly, Tween engine maybe?
First question here, so bare with me if I make a mistake or two. Long story short I'm currently developing a side scroller game in java with libgdx, which uses tiledmaps from the tiledmap creator software. When the player has run for some time the map is automaticly changed to a new one, using some code which looks similar to this:

void changeMap() { Gdx.app.postRunnable(() -\> { testMap = new TmxMapLoader().load("someMap.tmx"); renderer.getMap().dispose(); renderer.setMap(testMap); }); }

My problem is that the map is changed instantly with no smooth transition at all, like one sec the player is on the old map, the next he starts instantly on the new one, which is quilte unprofessional in My opinion. I would like to create some smooth transition between the two. Maybe just a simple fade in, fade out. Any thing is Better than how it is now.

I have searched google, tried different "solutions" using the tween engine, tried Making a transition screen which first fades in over the playscreen, but when i try to fade back the playscreen is just stoppede etc. I'm really emptied for ideas, so it would be awesome if one of you experts could point me in the right direction. Or maybe Come up with a simple solution. I am experienced with java so any idea here will be apriciated.

This is written from a phone, so sorry for any spelling mistakes.

# Answer
I would agree with using the `TweenEngine`. It's relatively simple to use and provides a lot of functionality. To tween a value you first have to create a `TweenAccessor`. It would look something like this for a `Sprite`:

```
public class SpriteAccessor implements TweenAccessor<Sprite> {

    //Used to identify what type of tweening you wish to do.
    public static final int ALPHA = 0;

    @Override
    public int getValues(Sprite target, int tweenType, float[] returnValues) {
        switch (tweenType) {
        case ALPHA: //If the tween type is ALPHA as defined above...
            //Set the returnValues to the alpha of the sprite.
            //returnValues is the array of values we wish to tween (change).
            returnValues[0] = target.getColor().a;
            //Then return the number of values you changed in the array.
            return 1;
        default:
            assert false;
            return -1;
        }
    }

    @Override
    public void setValues(Sprite target, int tweenType, float[] newValues) {
        switch (tweenType) {
        case ALPHA:
            Color color = target.getColor(); //Get the sprite color
            //Here we set the alpha to the tweened alpha value we entered
            //above.
            target.setColor(color.r, color.g, color.b, newValues[0]);
            break;
        default:
            assert false;
        }
    }

}

```

Then you would use it like this:

```
Tween.to(yourObject, SpriteAccessor.ALPHA, anyDuration).target(anyAlphaValue).start(yourTweenManager);
//Changes the alpha value of yourObject from it's current value to anyAlphaValue.

```

Of course this `TweenAccessor` only works for `Sprite`s. You'd have to write your own for a `TiledMap`, or for whatever object you wish to tween. I can't give en example of a `TiledMap` alpha tween right now as I don't know from the top of my head how to change the color of a `TiledMap`, but I'm sure you can figure that out yourself.
> 0 votes

---
Tags: java, libgdx, game-design
---


# Question
Title: How To Extract A File In A Relative Location With Python?
I'm trying to extract a file with python 3(for my game launcher), and this is the code I'm using:

```
import zipfile
f = open('filenamehere.zip', 'rb')
z = zipfile.ZipFile(f)
for name in z.namelist():
    outpath = ""
    z.extract(name, outpath)
fh.close()

```

I can't seem to figure out how to change outpath to get it to put it in a relative position. .\_.

# Answer
Try this:

```
import os
myPath = os.path.join(os.getcwd(),'filename.zip')
f = open(myPath, 'rb')

```

It gets the current working directory and joins the file name.
> 1 votes

---
Tags: python
---


# Question
Title: Dynamic force behind logical jumping on 3 axis'
I've been working on physical jumping in a 3D environment, I've got it working with a static force. The problem with this is that the force on each axis should be different due to the rotation from the player.

A few things to keep in mind:

* A total rotation of 360 degrees can be made;
* Forces should never be greater than 0.2 or lower than -0.2;
* There is no framework/engine behind the game, it's all hardcore codings.

I've been trying something like;

```
velocity.x = x - ( x + ( 10 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );
velocity.y = y - ( y + ( 20 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );

```

where x,y is the spawned location and rz is the rotation from the player. This way, I'll get the location from the player 20 units in front of him. By subtracting the actual starting position from it, I should've gotten a velocity. However, this turned out to be wrong. It's not going towards the direction the user is facing, it's just doing it's own simple thing.

The jumping/throwing into 1 direction is working perfectly fine. The calculations I made so far are totally messed up and not working as expected.

The results which I am expecting to get is something like;

```
force.x = 0.1;
force.y = 0.2;

```

this can be negative or positive, this should be dynamic though.

# Answer
So first, in the formula:

```
velocity.x = x - ( x + ( 10 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );

```

The two 'x's cancel out each other:

```
x - (x + n)

```

is same as

```
x - x - n

```

Then to convert an angle to a vector you need to use **sin** AND **cos**.

```
velocity.x = speed * math.cos ( rz * math.pi / 180 );
velocity.y = speed * math.sin ( rz * math.pi / 180 );

```

In this case **rz** will indicate a counter-clockwise rotation if y increases vertically (clockwise if not), with 0 degrees being in the positive x direction (usually, to the right).

To have **rz** rotate the other way:

```
velocity.x = speed * math.cos ( rz * math.pi / 180 );
velocity.y = speed * math.sin ( rz * math.pi / -180 );

```
> 2 votes

---
Tags: mathematics, lua, jumping
---


# Question
Title: GLSL - Only draw arond point / flashlight effect
I'm currently trying to achieve a sort of flashlight effect in GLSL. I only want to draw textures within a certain distance of a specified point (the mouse position, for example). Here's a quick example drawing of the effect I wish to achieve:

I've successfully created a shader that checks the position from a certain point to the position of the fragment, and then discards the fragment if the distance is larger than the specified light radius. The frag shader looks like this:

```
#version 400

#ifdef GL_ES
precision mediump float;
#endif

in vec4 v_color;
in vec2 v_texCoords;
in vec2 v_position;

out vec4 outColor;

uniform sampler2D u_texture;
uniform vec2 u_mousePos;
uniform float u_lightRadius;

void main() {
    float distance = distance((v_position + 1.0) / 2.0, u_mousePosition);
    if(distance > u_lightRadius) {
        discard;
    }

    outColor = v_color * texture2D(u_texture, v_texCoords);
}

```

The problem with this shader is that the visible area isn't a circle, it's an elipse. This is obviously because the screen aspect ratio is not 1:1. I've tried multiplying the Y values of all of the position variables with a resolution uniform, but it still remains an elipse.

My other problem is that I wish to have smooth edges on my visible area. I've read up some on the subject and I see that you can use `mix` and/or `smoothstep` to achieve this, but I'm unsure on how to implement it.

Anyone got any suggestions?

# Answer
> 1 votes
To fix the aspect ratio (and speed up the shader a bit):

```
void main() {
    vec2 diff = (v_position + 1.0) * 0.5 - u_mousePosition;

    diff.x *= u_aspect;  // e.g.: (16.0 / 9.0) for 16:9

    float distance = dot(diff, diff); // square of distance, saves a square-root

    if(distance > u_lightRadius_squared)) {
        discard;
    }

    outColor = v_color * texture2D(u_texture, v_texCoords);
}

```

To get a smooth edge remove the `if(...)discard` and add at the end:

```
outColor.a *= 1.0 - smoothstep(u_lightRadius_minus_one_pixel, u_lightRadius_plus_one_pixel, sqrt(distance));

```

For a less perfect but faster version:

```
outColor.a *= 1.0 - smoothstep(u_lightRadius_minus_one_pixel_squared, u_lightRadius_plus_one_pixel_squared, distance);

```

You can add back `if(outColor.a <= 0) discard;` at the very end to eliminate transparent pixels.

---
Tags: libgdx, shaders, glsl, lwjgl, fragment-shader
---


title: Adding a Scriptable Object to the Scene

text:
# Question
Title: Adding a Scriptable Object to the Scene
Suppose a `Scriptable Object` e.g. `NewWeapon.asset` with variables such as `name`, `description`, `price` etc.

I've also added a `public GameObject weaponObject;` so that I can drag and drop the 3D model related to this weapon.

Since `Scriptable Objects` cannot be added in a scene, how can I add a `GameObject` in the scene with an attached script that will *draw* data from the `NewWeapon.asset` and display the `3DModel` already specified and load up the rest of the variables?

My goal is to create a script `Item.cs` which will be attached to a `GameObject` in the scene and then based on the current `ScriptableObject` load its name, stats and `3Dmodel`

# Answer
> 2 votes
`ScriptableObject`s are not components, so you can't add them with "Add Component". But they can be properties of components.

When you create a variable `public ScriptableObject foo` (or of a class which extends ScriptableObject) in a MonoBehaviour and then add that MonoBehaviour to the scene, you get a box for it in the inspector to which you can drag-and-drop a ScriptableObject.

Example script:

```
using UnityEngine;

public class ThingWhichHasAScriptableObject : MonoBehaviour {

    public ScriptableObject assignedAsset;

}

```

A GameObject with that component in the editor:

You can now drag your `NewWeapon.asset` into the "Assigned Asset" slot and then interact with it from the `ThingWhichHasAScriptableObject` script.

Regarding displaying a 3d model assigned to the ScriptableObject: Just assigning the ScriptableObject to a GameObject in your scene won't cause it to be rendered. You will have to `Instantiate` that 3d model at runtime.

---
Tags: c#, unity
---


# Question
Title: How to combine dynamic asset reload and texture atlases? (rectangle packing with removal)
Usually *texture atlases* are built either:

* as a seperate content pre-processing step
* or once when the game starts

What I want to do is create and update atlases on the fly when:

* A new texture file appears on the disk (or when a file gets removed)
* Pixel data and/or size of the texture changes (file gets changed)

As a seperate use-case - it's also useful when all assets can't be loaded in memory at once:

Different subsets of textures are used within different levels (yet are not set in stone as player can *bring* new assets from another level, or find a *random drop* which introduces a new texture from a vast library).

There a wealth of information on texture-packing algorithms in a *all at once* scenarios.

What algorithms are there for packing atlases dynamically (*add/remove/resize texture*)?

**What rectangle packing with removal algorithms are there?**

* Textures of arbitrary size
* Multiple power-of-two bins
* Both adding and removing has to be *fast* and *online*
* Removal operation should NOT trigger repacking of the whole atlas. Moving an occupied rectangle or two is acceptable (but better avoided?).

# Answer
I ended up implementing a Guillotine rectangle packing algorithm (with heuristic for picking free rectangles with smallest area) GUILLOTINE-BAF with some modifications:

1. When a texture gets removed - the freed up space gets merged with other free rectangles that are adjacent and their width or height matches (this is done multiple times until there's nothing left to merge with the freed rect).
2. When there's no free space for the new rectangle to be packed a new bin (atlas) is added.
3. When a dimension of a texture is changed (with filesystem change notification), the rectangle is repacked in the current atlas, if not - it's moved to another atlas with free-space.
4. Each atlas stores largest free pixel area, biggest rectangle width and height to find if atlas has enough space for a particular rectangle without going through the free rectangles list.

This method is simple to implement, online, it is fairly fast (fast enough). It does introduce some fragmentation.
> 1 votes

---
Tags: algorithm, texture-atlas, hot-reload
---


# Question
Title: Gamemaker's xprevious is the same value as x... Same thing happens for the y variabbles
So I'm making a tower defense game but for some reason the enemies (which are following a path) have the same xprevious value as their x value. The same is true for their y variables. This also happens when the enemy is not on a path. I double checked that I'm not modifying the x and y previous variables anywhere. Is this a bug in GameMaker?

Thanks, Philip

# Answer
GameMaker automatically stores `x` and `y` to `xprevious` and `yprevious` just before `Begin Step` event.

If object moves using paths, then position (`x` and `y`) of the object will be changed after `Step` event and before `End Step` event. So, before `End Step` coords and previous coords will be same, but after `End Step` it will be different.
> 1 votes

---
Tags: game-maker
---


title: Faking 3D in a mostly 2D game

text:
# Question
Title: Faking 3D in a mostly 2D game
I want to create a sports simulation game, something along the lines of Championship Manager (if you're not familiar, you can check out https://www.youtube.com/watch?v=t2FlFWP3K28). It's essentially a 2D game with top-down view, with the exception that the ball seems to behave as if it was 3D.

Given that the game is almost entirely 2D and only the ball is 3D, is there a good way to deal with that without making an entirely 3D game just because of the ball? Can the ball be hooked into a 3D physics engine, the rest to a 2D engine and somehow reconcile the two, then when rendering, just make the ball grow the higher it goes and show a shadow, or something along those lines?

# Answer
You can achieve the effect of the ball by modifying two things: 1. The game object's size. Whenever the ball is kicked modify it to match the specific action, like a long lobbed pass will make the ball bigger. 2. The texture that is being applied to. Make the texture repeat itself on the direction it is going. For example a forward pass will make the texture move forward (repeated tiling) and a swerve will move it on the x and y axis at the same time, making the ball look like it is spinning.

Combine both to achieve the desired effect. The shadow can be another spherical game object with varying alpha values (transparency).
> 1 votes

# Answer
I would just cheat and use the formula for a parabola. The ball sprite can be sized based on the height of the parabola.
> 0 votes

# Answer
The game is either doing some trickery to achieve a 3D like trajectory (sine waves, parabolas, etc) or using actual 3D math.

Then, they simply take the 3d coordinates, and render the ball larger or smaller depending on the depth. Essentially rasterizing.

Shadows are achieved either again with 3d math by projection or simply faking it again with a simple distance algorithm (shadow position.x = ball position.x - ball.position.z * some scale)
> 0 votes

# Answer
You can make the shadow by simply parenting a Sprite with a black circle and adjusting it to be below the ball so that when ball moves this Sprite moves and it looks like shadow. The 3D effect by changing scale depending on the depth or use triggers to shrink it on entry.
> 0 votes

---
Tags: 2d
---


title: Draw a square given 2 corners

text:
# Question
Title: Draw a square given 2 corners
I am at the moment trying to come up with a simple method to extract some data points, given two corners.

```
A***************
****************
***************B

```

I tried to illustrate my situation above.
Given corner A and B (x,y,z) how do generate the (x,y,z) coordinate for all the * in the square?

# Answer
I assume you use integer for the coordinates. You could do something like the following:

```
for (int z = A.z; z <= B.z; z++) {
    for (int y = A.y; y <= B.y; y++) {
        for (int x = A.x; x <= B.x; x++) {
            // Do things here.. You can get the coordinates from the x, y, and z variables.
        }
    }
}

```

This will basically iterate through every point (\*) including the point given (A and B).

---

I don't know what you're looking for but it seems to me this is what you ask.

Here's a fast example without using z (tested with cpp.sh):

```
// Example program
#include <iostream>

struct point {
    int x, y, z;
} A, B;

int main()
{
    A.x = 3;
    A.y = 4;
    //A.z = 0;

    B.x = 7;
    B.y = 5;
    //B.z = 0;
    //for (int z = A.z; z <= B.z; z++) {
        for (int y = A.y; y <= B.y; y++) {
            for (int x = A.x; x <= B.x; x++) {
                // Do things here.. You can get the coordinates from the x, y, and z variables.
                if (x == A.x && y == A.y) printf("A[%i, %i]", A.x, A.y);
                else if (x == B.x && y == B.y) printf("B[%i, %i]", B.x, B.y);
                else printf("[%i, %i]", x, y);
            }
            printf("\n");
        }
    //}
}

```

Example above will print all the coordinates like so: `[x, y]`. Oh, and also the above example won't work if B is smaller than A.. Need to do something about that, probably a check or even a dynamic approach.
> 1 votes

---
Tags: c++, geometry
---


# Question
Title: Why is my player object not being clamped?
I have a game object that has specific boundaries. However, when I have the object meet the boundaries, the object doesn't stop the way it's supposed to, it continues to move past the set boundaries. Can anyone explain why this would be happening and how to fix it?

**Player Object public variables**

**C#**

```
using UnityEngine;
using System.Collections;

public class PlayerController:MonoBehaviour{
    public Rigidbody player;
    public float bankSpeed;
    public float bankRotation;
    public float pitchSpeed;
    public float pitchAngle;
    public float xMin, xMax, yMin, yMax;
    public ChangeCamera changeCamera;
    void Start(){
        player = GetComponent<Rigidbody>();
        changeCamera.isThirdPersonView = false;
        changeCamera.isTopDownView = false;
    }

    void FixedUpdate(){
        if(changeCamera.isThirdPersonView == true){
            changeCamera.isTopDownView = false;
            thirdPersonControls();
        }
        if(changeCamera.isTopDownView == true){
            changeCamera.isThirdPersonView = false;
            topDownControls();
        }
    }

    void topDownControls(){
        float moveVertical = Input.GetAxis("Vertical");
        float moveHorizontal = Input.GetAxis("Horizontal");
        Vector3 bank = new Vector3(moveHorizontal, 0f, 0f);
        Vector3 moveForward = new Vector3(0f, 0f, moveVertical);
        player.AddForce(bank * bankSpeed);
        player.AddForce(moveForward * pitchSpeed);
        topDownRotation();
    }

    void thirdPersonControls(){
        float moveVertical = Input.GetAxis("Vertical");
        float moveHorizontal = Input.GetAxis("Horizontal");
        Vector3 bank = new Vector3(moveHorizontal, 0f, 0f);
        Vector3 pitch = new Vector3(0f, moveVertical, 0f);
        player.AddForce(bank * bankSpeed);
        player.AddForce(pitch * pitchSpeed);
        thirdPersonRotate();
    }

    void topDownRotation(){
        player.rotation = Quaternion.Euler(0f, 0f, (player.velocity.x * -bankRotation));
        player.position = new Vector3(Mathf.Clamp(player.position.x, -15.25f, 15.25f), 0f, Mathf.Clamp(player.position.z, 1f, 18.25f));
    }

    void thirdPersonRotate(){
        player.rotation = Quaternion.Euler((player.velocity.y * -pitchAngle), 0f, (player.velocity.x * -bankRotation));
        player.position = new Vector3(Mathf.Clamp(player.position.x, xMin, xMax), Mathf.Clamp(player.position.y, yMin, yMax), 0f);
    }
}

```

Basically, the way it works is, the player moves in any direction(up, down, left, right) and when they hit the edge of the screen, they're supposed to stop, which they do, however, if they continue to press the button that moves them, they'll continue to move off screen, very slowly. How do I prevent this from happening?

Dropbox Link

# Answer
When you use the Unity rigidbody physics to control the movement of an object (like implied by using AddForce) you should generally not manipulate its transformation directly. Doing so can cause lots of weird behaviours.

If you need to constrain objects, place an invisible object with an appropriately shaped collider in the way.

Regarding *why* this is happening in this case, what happens every frame is:

* You add a force to the object with `AddForce`
* You set the `transform.position`
* Code execution leaves your code and enters the Unity physics engine, which:
    + Checks the current forces added to the object
    + Calculates an acceleration vector
    + Adds that acceleration vector to the current speed vector
    + moves the object by that speed, beyond the position limit you set through clamping
* The frame is rendered to the screen

The object slowly moves further into the "forbidden zone" every frame because the player adds more and more speed to it which translates to a further and further offset.
> 1 votes

# Answer
If you don't want to use planes or cubes to set the boundaries for your player object, the simplest way to accomplish this would be to remove the player object's velocity and angular velocity all together. Simply write a conditional which checks to see if the player object's position is at the desired boundary position. If it is, remove the velocity, like so:

```
if((player.position.x == xMin) || (player.position.x == xMax) || (player.position.y == yMin) || (player.position.y == yMax)){
    player.velocity = new Vector3(0f, 0f, 0f);
    player.angularVelocity = new Vector3(0f, 0f, 0f);
}

```
> -1 votes

---
Tags: c#, unity
---


# Question
Title: NullReferenceException being thrown when I try to add a component to a dictionary
I have the following section of code from a `MonoBehaviour` class in a voxel engine that I'm currently working on right now:

```
public void CreateChunk(Position chunkPosition)
{
    GameObject newChunk = (GameObject)Instantiate(
        this.ChunkPrefab,
        new Vector3(chunkPosition.X, chunkPosition.Y, chunkPosition.Z),
        Quaternion.identity
    );

    Debug.Log("New Chunk", newChunk);

    Chunk newChunkComponent = newChunk.GetComponent<Chunk>();
    newChunkComponent.ChunkPosition = chunkPosition;
    newChunkComponent.ParentTerrainManager = this;

    this._ChunksInMemory.Add(chunkPosition, newChunkComponent);

    for(int x = 0; x < Chunk.GlobalChunkSize; x++)
    {
        for(int y = 0; y < Chunk.GlobalChunkSize; y++)
        {
            for(int z = 0; z < Chunk.GlobalChunkSize; z++)
            {
                newChunkComponent.CreateBlock(new Position(x, y, z), new Stone());
            }
        }
    }
}

```

The `Chunk` class is also a `MonoBehaviour` class as well. I'm trying to instantiate a chunk prefab and then get the `Chunk` component from the instantiated prefab. Unfortunately I get the following `NullReferenceException`:

> ```
> NullReferenceException: Object reference not set to an instance of an object
> Voxel.Engine.TerrainManager.CreateChunk (Position chunkPosition) (at Assets/Source/Engine/TerrainManager.cs:99)
> Voxel.Engine.TerrainManager.Start () (at Assets/Source/Engine/TerrainManager.cs:132)
>
> ```

This is line 99:

```
this._ChunksInMemory.Add(chunkPosition, newChunkComponent);

```

The field `this._ChunksInMemory` is simply a `Dictionary<Position, Chunk>` containing all the currently loaded chunks.

I have done the following things so far:

* I have confirmed that the `TerrainManager` `MonoBehaviour` class (the one that contains the above section of code) does in fact have a chunk prefab assigned:
* I have confirmed that there is in fact a copy of the chunk prefab by looking at the hierarchy and calling `Debug.Log("Chunk created", newChunk)`.
* I have confirmed that the copy of the chunk prefab has a `Chunk` component attached to it:

At this point, I am clueless as to why my code isn't working. Just from looking at the code, it should work fine, but it doesn't. Does anyone know why this is happening?

# Answer
> 2 votes
Based purely on the code you posted, the only object that can be null and cause an NPE is `this._ChunksInMemory`. It is highly probable that you declared it and forgot to define it with `new`. Comments indicate I was correct in this assumption.

I see this sort of problem all the time, particularly with new coders (and sleep deprived). NPEs are among the easiest errors to diagnose and fix. By knowing what line it occurs on you can use a multitude of debugging techniques to inspect each object on that line to determine which one is null. Cameron Oltmann's reply about the manual debugger is one such way. Another is to use `Debug.Log(...)` messages to print out the value of each object on the offending line (although unity will frequently print an empty string for a null object, I don't know why and wish it wouldn't).

---
Tags: unity
---


title: How to rotate a 2d line?

text:
# Question
Title: How to rotate a 2d line?
Its a very simple question. How can i rotate a line by one of its endpoints by the angle rad?

Heres my current code ( I couldnt find a different solution )

```
void displayPlayer() {
    float rad;
    putpixel(x, y, 10);
    if (view > 360)
        view = 0;
    nx = (int)round(x*cos(view) - y*sin(view));
    ny = (int)round(x*sin(view) + y*cos(view));
    rad = (double)view / 180.0 * M_PI;
    line(x, y,nx,ny);
    putpixel(cos(rad)*(x + 10) - sin(rad)*(y + 10), sin(rad)*(x + 10) + cos(rad)*(y + 10), 10);

}

```

Heres a litte visualisation of my result:

The line is supposed to be 10 px long and keep rotating 360°. Ive indicated its origin with a green line.

What am I doing wrong?

# Answer
It could be your `view` as it is not to be in radians as you can see by `if (view > 360)` which indicates degree. And you use it in sin and cos.

Or

It seems to me, your `nx` and `ny` use a rotation matrix which rotates relative to origin \[0, 0\] with the distance to the origin x and y. If you are going to use that, change x and y to something like x1-x and y1-y with x1 and y1 the point you want to rotate relative to x and y. After doing all that, sum it with x and y at the end again.

```
int dx = x1-x, dy = y1-y;
nx = dx * cos(ang) - dy * sin(ang) + x;
ny = dx * sin(ang) + dy * cos(ang) + y;

```

If you haven't noticed yet, dx and dy is the horizontal and vertical distance from the point of rotation. Not the distance (which you probably want to be 10, see below)

If you already know the distance there is another good approach you can read here as it is pretty much the same question. It is simpler and easier if you ask me (Choosen answer). Rather than using something like matrix (You can see my answer there too).
> 2 votes

---
Tags: c++
---


title: How to make an Actor follow my finger

text:
# Question
Title: How to make an Actor follow my finger
I'm back with another question that may be really simple.

I've a texture drawn on my spritebatch and I'm making it move up or down (y-axis only) with Libgdx's Input Handler: touchDown and touchUp.

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    myWhale.touchDownY = screenY;
    myWhale.isTouched = true;
    return true;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    myWhale.isTouched = false;
    return false;
}

```

myWhale is an object from Whale Class where I move my texture position:

```
public void update(float delta) {
    this.delta = delta;
    if(isTouched){
        dragWhale();
    }
}

public void dragWhale() {
    if(Gdx.input.getY(0) - touchDownY < 0){
        if(Gdx.input.getY(0)<position.y+height/2){
            position.y = position.y - velocidad*delta;
        }
    }
    else{
        if(Gdx.input.getY(0)>position.y+height/2){
            position.y = position.y + velocidad*delta;
        }
    }
}

```

So the object moves to the center of the position where the person is pressing his/her finger and most of the time it works fine but the object seems to take about half a second to move up or down and sometimes when I press my finger it wont move.

Maybe there's another simplier way to do this. I'd highly appreciate if someone points me on the right direction.

# Answer
> 1 votes
Try to extend the whale as an `Actor` and add an `ActorGestureListener` to it. Use the pan function to drag the whale. It will be something like this:

```
void pan(event, x, y, deltaX, deltaY){
    myWhale.position.add(deltaX, deltaY);
}

```

And I think you'll have to use `Stage` for that, but I'm not sure.

# Answer
> 0 votes
No need to take an extra class for Input just write the following code in render method :-

```
if (Gdx.input.isTouched())
 {
    Rectangle   touchRectangle = new Rectangle(Gdx.input.getX( ),
                        Gdx.graphics.getHeight() - Gdx.input.getY( ), 10,
                        10);

//just check if your finger overlaps on your character then move according to it
                if (touchRectangle
                        .overlaps(whaleRectangle)) {
                      whaleRectangle.x=Gdx.input.getX();
                      whaleRectangle.y=Gdx.input.getY();

   }
   }

```

# Answer
> 0 votes
If your class implements InputProcessor:

```
  @Override
  public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    MoveToAction mta = new MoveToAction();
    mta.setPosition(screenX, Math.abs(stage.getHeight()-screenY));
    mta.setDuration(5f);  //moves to new location by this time interval
    stage.addAction(mta);
    return false;
  }

```

---
Tags: java, android, game-design, libgdx
---


# Question
Title: Unity3D - Smooth rotation for seek steering behavior
I am trying to implement Reynolds' seek steering behaviour, but I am having problems on the rotation part. This is what I have:

```
void FixedUpdate()
{
// get position of current waypoint
        Vector3 targetPos = new Vector3(path[currentWaypoint].x, transform.position.y, path[currentWaypoint].z);

        // velocity vector towards target
        Vector3 desiredVelocity = targetPos - transform.position;

        // calculate the steerforce required for the desired velocity based on current velocity
        Vector3 steerForce = desiredVelocity - currentVelocity;
        steerForce = new Vector3(steerForce.x, 0, steerForce.z);
        steerForce = Vector3.ClampMagnitude(steerForce, maxSteer);

        // create a move vector to be added to agent's current position
        // Then normalize it so it can be scaled according to the agent's max speed
        Vector3 moveVector = steerForce.normalized * moveSpeed * Time.fixedDeltaTime;
        transform.Translate(moveVector);
}

```

How would I do it so my agent will be rotated smoothly based only on the code above? I tried rotating based on the current velocity, but the agents is rapidly rotated in one frame towards the target waypoint. I am not working with rigidbodies.

Am I doing something wrong? What am I missing?

Thanks, Jack

# Answer
> 0 votes
After looking up how Reynolds seek steering works i realised that lerping wouldn't work. What you have to do is limit the steering to the maximum force which should be set very low to avoid instant steering.

```
void FixedUpdate()
{
    //move to position
    transform.Translate(Seek(new Vector3()) * Time.fixedDeltaTime);
}

Vector3 Seek(Vector3 target)
{
    //Reynolds steering behaviour = desired - velocity
    //Should be global variables
    float maxSpeed = 4f;    //fastest possible speed
    float maxForce = 0.1f;  //turning speed of the object

    //the direction that you need to go to reach the target
    Vector3 desired = target - transform.position;
    desired.Normalize();
    desired *= maxSpeed;

    //steering (reynolds steering)
    Vector3 steer = desired - currentVelocity;
    steer.y = 0f; //assuming you want 2D motion on the XZ plane

    //limit the steering
    if(steer.sqrMagnitude > maxForce * maxForce)
    {
        steer.Normalize();
        steer *= maxForce;
    }

    return steer;
}

```

This should work but it's untested. Tell me if there is a problem with it. You will **need to change** the target location in the update method as i doubt that you want to go the the origin of the scene.

**EDIT**

To get the rotation to work you need to get the object to face into the direction that it is moving. So by changing the update function too this it should work (in theory):

```
void FixedUpdate()
{
    transform.Translate(Seek(new Vector3()) * Time.fixedDeltaTime);//change position
    transform.rotation = Quaternion.LookRotation(currentVelocity);//change the rotation
}

```

# Answer
> 0 votes
I have a MathHelper class for stuff like this (I've got a fast/inaccurate distance check, various radians-degrees conversions, this angle trig, safe angle addition, a snap method...). Here's the one that is of interest to you:

```
public static double AngleBetweenPointsRadiansDouble(Vector2 P1, Vector2 P2) {
    return Math.Atan2( ( P2.y - P1.y ), ( P2.x - P1.x ) );
}

```

You'd want to plug in Vector2 versions of your Vector3s's `.x` and `.z` (as you are ignoring the Y component).

```
Vector2 pos = new Vector2(transform.position.x,transform.position.z);
double angle = MathHelper.AngleBetweenPointsRadiansDouble(pos, pos+moveVector);

```

You'd want to convert this to degrees and then apply it to the transform's eulerAngles's Y component.

---
Tags: unity, rotation, ai, steering-behaviors
---