# Question
Title: SFML - Difficulty with Rect Motion when using 1028x720 image per frame
Hello their just having a little tediously annoying problem that I just can't seem to figure out I've tried numerous things from using for loops on iterators and index values , iterating a index for the usual switch statement "switch(index)" then rendering the image per frame also tried rendering per delta time all leading to pretty poor results such as the frames would change but each frame index would have it's own unique time it took to change too the next frame was rather bizzare actually anyways the problem is "sorry for that long introduction" :

I'd like to render a HD image animated background in my video game using SFML and C++ .

The problem is that it won't change the index slow enough even when using delta time "sf::clock deltaclock = sf::asMilliseconds" , frameratelimiting and or verticlesync also won't move the clip rectangle for the texture correctly enough to give the illusion of an animated hd image...

Id show code but I think the problem doesn't require it at all unless for showing how to do the solution all I want is too be able to simply move a clip rect a certain amount on a 1 HD image per frame for a 3 frame HD spritesheet using SFML and C++.

What that means is I have 3 HD images of 1024 width and 720 height at different locations on a spritesheet and Id like to use a clip rectangle too move across this spritesheet fast and correctly enough to give the illusion that the 3 HD images as a whole 1 HD image are animated in game without any suttering , lagging or way to fast speeds.

one solution I had was too use a sprite sheet and split up the entire background into little tiles and render them all seperatly using a tilemap text file with numerical digits in it representing certain tiles,etc ... but that seems overkill.

Thank you in advance

# Answer
So from what I could gather what you are looking for is a simple frame-based sprite animation. This is a common approach that's used when games don't animate objects by moving smaller parts of the objects programmatically, but instead prerender the animation states into an image file.

Now, there are a few different approaches to how the images are stored. If your frames aren't stored right next to each other, you might want to use a spritesheet builder too, that will export positions and spritesheets for you. That way, all you probably have to do is to load the rectangle positions from a content file (JSON, XML or something else), to an array, and index that array by your current frame index.

The way I handle frame-based animating, is that I position my frames right next to each other in a separate image file made just for the animation I want to implement. This makes calculating the rectangles super easy. You probably want to save the rectangles also to an array.

```
Rectangle[] calculateRectangles(int frameWidth, int frameHeight, Image image)
{
    Rectangle rectangles[];

    for (int y = 0; y < image.Heigth; y += frameHeight)
    {
        for (int x = 0; x < image.Width; x += frameWidth)
        {
            rectangles.push_back(Rectangle(x, y, frameWidth, frameHeight));
        }
    }

    return rectangles;
}

```

The pseudo-code above calculates the rectangles for a generic spritesheet/tileset. It assumes that the whole image is filled with the frames. You could modify this to ignore rectangles after *N*-rectangles. The code flow should be quite simple to follow trough: it simply goes trough the frames row by row, column by column. You would then save the array returned to the corresponding class.

You then simply increment your frame index once in a while, calculating timed intervals is a different question, but I'm sure SFML offers utilities to do this. On render, you simply then use the rectangle in the array at the correct index.

Just to clarify, the image file could look something like this (I'm not sure about texture size limitations, you could also put the frames all below each other, or two on one row, one on the next).
> 1 votes

---
Tags: c++, sfml
---


# Question
Title: How do I make a quake-style camera tilt in Unity?
I want to make a retro-styled game with a modern look to it, and to do so I wish to make a quake-styled camera tilt. By that I mean when moving sideways the FPS Camera tilts a little bit, and the returns to default when letting go of the key. I have little to no scripting knowledge.

https://www.youtube.com/watch?v=scSea\_v7JHA

Notice how in the video when moving to the side the camera tilts a little-bit.

# Answer
> 1 votes
Attach the following script to your Camera. You can set the variables from your editor. I would advice you to get into scripting if you want things like this to happen.

EDIT: This code rotates the camera on its Z axis once per frame, when during this frame it detects a KeyDown event. When detecting the KeyUp event it rotates it back to its original Z value, nullifying the tilt.

```
using UnityEngine;
using System.Collections;

public class CamTilt : MonoBehaviour {

    //Editor variables, you can customize these
    public float _tiltAmount = 5;
    public KeyCode _leftBtn = KeyCode.A; //A is default
    public KeyCode _rightBtn = KeyCode.D; //D is default

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

         // If _leftBtn key is hit, rotate Z axis of camera by _tiltAmount
        if (Input.GetKeyDown (_leftBtn)) {
            this.transform.Rotate (0, 0, _tiltAmount);
        } else if (Input.GetKeyUp (_leftBtn)) {
            this.transform.Rotate (0, 0, -_tiltAmount);
        }

        // Same as above, but inverted values
        if (Input.GetKeyDown (_rightBtn)) {
            this.transform.Rotate (0, 0, -_tiltAmount);
        } else if (Input.GetKeyUp (_rightBtn)) {
            this.transform.Rotate (0, 0, _tiltAmount);
        }
    }
}
```

---
Tags: unity, camera
---


# Question
Title: How to achieve light effect on a car panel icons?
I'm making a car and I want to make lightable icons on its panel. I want to add 'on' and 'off' effect to them separately. The Sprites are plane objects, with one material and UV texture for each plane.

If I change material property - it will change in all objects which use this material. I don't think creating 10 materials for 10 sprites is the best choice, what should I do in this situation?

# Answer
> 0 votes
Make each icon a separate game object with its own `Renderer`. You can use the same material for all of them when you create a texture with all the icons and then use the UV coordinates of each plane to only show the icon it is supposed to represent.

Create two versions of the material, one for "on" and one for "off". Then you assign the appropriate material to the buttons when they are on or off.

Alternatively you can add a script to the icons which uses `renderer.SetPropertyBlock` to set individual properties for the renderer of that object. You can use that to change the albedo color and/or emission color without creating a duplicated material or affecting the other renderers.

---
Tags: unity, sprites, lighting
---


# Question
Title: How to make a road terrain for unity game?
im making a FP game in low poly style. I want to make some terrains for my game, with roads, trees, rocks, buildings and e.t.c. Unity terrains are not as good as i thought. They allow a good tool for placing multiple objects (like tree-to-sprite tools, trees mesh copy for perfomance), but the terrain building tool itself is very poor, so i cant use 3d terrain, because there will be no great tools for placing surroundings.

So my plan is - make low poly mountains, trees, rocks in Blender, then make a simple terrain with hills in unity and just place my surrounding objects on it. I have some troubles, for example - roads. I have a road elements, and by connecting & banding them i can get a really nice road. But how can i make a road on Unity's terrain?

For example it could be useful to export unity terrain as a 3d mesh to Blender, then make my roadways and export them in Unity.

# Answer
You could concider making the terrain and road in blender and use those in unity. Blender has the power to generate heightmaps from objects, in case you dont want to use the object itself.
> 3 votes

---
Tags: unity, terrain, low-poly, asset-creation
---


# Question
Title: Garry's Mod gamemode scripting (lua) - How do I tell if an object is inside a hollow cylinder?
I'm fiddling about with gMod trying to make a gamemode where you have to throw a piece of cake into a cylinder that spawns on the map.

This is the code I'm using to spawn the cylinder:

```
local ent = ents.Create( "prop_physics" )
ent:SetModel("models/props_phx/construct/windows/window_curve360x1.mdl")
ent:SetPos( Vector(math.random(100,2500), math.random(1500,-1000), 150) )
--ent:SetPos( math.random(-1500,-2500), math.random(-1500,-2500), 100 )
ent:Spawn()

cleanup.Add( self.Owner, "props", ent )

undo.Create( "Spawned_Cylinder" )
undo.AddEntity( ent )
undo.SetPlayer ( self.Owner )
undo.Finish()

```

The cake throwing part is basically just a SWEP that shoots the 'cakehat' prop. How would I test whether there is a piece of a cake inside the cylinder?

# Answer
You take the center of the cake and determine if it's within distance of the radius and also within the distance of the height. It's been a while since I've done gmod lua so bear with me.

```
local cylinderCenterPos = Vector(0,0,0)
local cylinderHeight = 2
local cylinderRadius = 2
local cakePos = cake.GetPos()

local radiusDist = math.sqrt(math.pow(cylinderCenterPos.x - cakePos.x,2) + math.pow(cylinderCenterPos.y - cakePos.y,2)) --Horizontal axes
local heightDist = math.abs(cylinderCenterPos.z - cakePos.z) --Up axis

if radiusDist <= cylinderRadius and heightDist <= heightDist then
    --The cake is in the cylinder
end

```

Note that this will test if the center of the cake is within the cylinder and assumes a cylinder that's height is running along the up vector.

Checking on a rotated cylinder is a bit harder as you have to check using the transformed axis of the cylinder (however it's rotated).
> 1 votes

---
Tags: collision-detection, vector, lua, modding
---


# Question
Title: What component should hold the bool attack and vector target?
I am having trouble thinking of what component should hold the attack and target data. In the below code components are holding a redundant data which I want to eliminate.

```
public class PlayerComponent implements Component {
    public boolean attack = false;
    public Vector2 target = new Vector2();
}

public class PoliceComponent implements Component {
    public boolean attack = false;
    public Vector2 target = new Vector2();
}

public class CriminalComponent implements Component {
    public boolean attack = false;
    public Vector2 target = new Vector2();
}

```

I ended up creating an `CombatComponent` that holds the both attack and target, but I doubt there is more better way. The purpose is to have a weapon system the check if the player or enemy trigger attack and get its target.

```
private void processWeapon() {
    for (Entity weapon: weaponEntities) {
        AttachmentComponent attachment = Mapper.attachment.get(weapon);
        if(playerFamily.matches(attachment.owner)) {
            PlayerComponent player = Mapper.player.get(attachment.owner);
            CombatComponent combat = Mapper.combat.get(attachment.owner);
            if( combat.attack ) {
                WeaponComponent weaponComponent = Mapper.weapon.get(weapon);
                weaponComponent.use = true;
                weaponComponent.target.set(player.target);
            }
        }
    }
}

```

or the another way calling the `WeaponSystem` to use the owner weapon.

```
getEngine().getSystem(WeaponSystem.class).useWeapon(ownerEntity, targetPosition);

```

# Answer
> 1 votes
The notion of a `target` I believe can go beyond the scope of just combat.

For example, perhaps you need to interact with another player and trade an in-game item between them. You typically click on the targetted player, right click their portrait and select 'Trade'. Another scenario may be to click on an NPC and right click to display a specific dialog window.

In either of the above scenarios, there is the concept an `TradeSystem` and `InteractionSystem` that are all based around what the player currently has targetted (selected).

The combat system would be no different. It checks to see whether the current entity has a target, displays an error perhaps if not otherwise uses the target component to obtain the target entity reference and performs the appropriate combat actions.

# Answer
> 1 votes
Not sure if this exactly meets your needs, but you could also create a separate POJO that encapsulates `attack` and `target` and use this inside `{Player|Police|Criminal}Component` (composition!). You'd still have a little duplication (instantiating this POJO in each of the three classes), but not all duplication is bad, and it's just one line.

---
Tags: libgdx, entity-system, entity-component
---


title: Chatbot AI game

text:
# Question
Title: Chatbot AI game
I was looking into getting started with AI and machine learning. As an excuse I wanted to try and make a chatbot centred game.

The idea would be to have the player stuck with a chatbot and only be able to interact or get information about the game world through the AI. Something a bit like Event\[0\], but without any graphics whatsoever. Basically an advance gamebook, or a role-playing game where the game master is an AI. Trying to replicate a simple murder mystery would be a start.

**Would it be feasible ?** Would an AI be able to create an adventure from scratch with just a few random seeds ? Could I train the AI using film or game scripts ?

**How long would it take?** Am I signing myself up for 2 years of coding ?

**Are there any opensource AI which can be downloaded and trained ?**

**What key issues do you think I overlooked ?** As I said I don't know much about machine learning. I have done two simple games using Pygame so far, a Zelda like and a Space Explorer, in both the AIs where scripted.

# Answer
**Would it be feasible?**

In short: yes, theoretically.

Long answer: It's going to take a while and it will be a lot of trial and error until you know what your doing then you have to figure out how to make the output from the machine learning make sense (I can almost guarantee it's going to butcher whatever language your going to try and teach it, at least for the first few attempts). It might be worth looking into making it detect what kind of tone you said it in, then generate a pre-defined bit of text in response. For example if someone if being a dick you might be harsh or possibly leave out a bit of information to make it harder for the player.

**How long would it take?**

Depends. what level of interaction do you want?

If you want every possible combination of words to be recognised properly you could be sat there for decades creating the singularity... On the other hand if you only want basic chat functionality you could have it done in a few months.

People have been trying to make proper chat programs for ages (at least 50 years) all of the attempts have taken a long time and produce mediocre results but on the other hand they are trying to make a program that is able to hold conversation to the level of the turing test. If you limited the scope and concentrated on building some way of extracting key words from the sentence then feed that into the machine learning portion you **might** be able to make something similar to what you want.

**Are there any opensource AI which can be downloaded and trained?**

There are a few out there but I don't know enough about them to tell you which ones would be good for this application.

Lucida AI, a program to make a virtual assistant think google search only locale on your machine.

Mahout, appears to be a library to enable scale-able machine learning. So you might want to look into this for the actual learning part as it should be able to scale so that you can get it to "learn" faster. small plus is that it's an Apache project so you can use it a for commercial software.

personally i'd take a small course into machine learning to see what your getting into to see if you could possibly stand spending an extended period of time developing. Udacity has a free course on it for deep learning which is a branch of machine learning or if your really dedicated this course specifically for machine learning however it costs a bit of money (200 USD with a 50% discount if you complete the course in a year).

**What key issues do you think I overlooked?**

In the end if your still going to make a game after going to all the effort of this, is it going to be a game that is "fun" or at least a game which will be an interesting and fun experience for the player that won't know the backstory of you developing an AI from the ground up. Will there be enough content to keep people engaged with it?

How are you going to get the AI to naturally get across narrative to the player without making it sound forced. An exelent example that i heard recently was that some scientists looked at a bunch of data and found a correlation between amount of Ice cream sold and people drowning. Someone without knowledge might think that they are linked but with context you realise that it's Summer and people are hot so they eat Ice cream and go swimming. How would your program deal with the context of the story without jumping to extremely strange conclusions?

What do you expect the player to be using to run the game? As far as i know must methods for interacting with such an AI that you want to develop required quite high end hardware. While most of this will be dependant on you training it (I assume) that there will still be a significant burden on players CPU if they expect to have good response times. You could try offsetting this by using the GPU to do some of the work (see CUDA CUDINN and OpenCL).

What happens when the game is running on a netbook without a GPU? could you get away with adding some story element that would allow for long waiting times between responses? on a different plant to the person that your talking too so you have to wait for the signal to reach them and travel all the way back? (As for as i can remember Earth to Mars is around 12 mins?)

**EDIT**

I'd also look into old text only games to see how they do it. I think most of they are just multiple choice but some of the lucusArts games had a small box were you could type in a question and based on some keywords it would give you a different response than the standard dialog options. Look into those and think about how an AI would improve those scenarios, Zork, Colossal Cave Adventure, etc. there are lots that have been ported to browser so you can just try them for a bit to get a feel of how they work.
> 1 votes

# Answer
**Would it be feasible?**

Probably. As for making seeded adventure plots, there is some background that needs to go into this. Your AI must first be able to communicate the plot, so there must be some pre-formulated sentences it can use to describe plot elements. Also, the bot needs to be able to determine a good plot from a boring one, so you might need to hard code in things like adventure length and difficulty. Training it using film scripts? This is a much bigger project. In theory, it could probably be done, but in practice you'd have to run many scripts through it, and your training program would have to be able to identify protagonists and plot devices, which can sometimes be very subjective (try running the script of Primer).

**How long would it take?**

This depends on your level of coding knowledge. If you're just starting out, I wouldn't recommend such a project, unless you don't plan on finishing it. You might learn a lot on the way, but if you don't already understand it, you'll get bored quickly.

If you are experienced, this could still take a while, possibly years depending on how much of your spare time you want to dedicate to it. There are several coding challenges I can see just from your proposal, and most of them have to do with the difficulty of programming an AI that learns anything. Whole teams of people work on projects that make AI's identify species of birds based on their pictures, so delegating that amount of work to one person is a lot to do.

**Are there any open source AI that can be trained?**

A quick Google search will result in a few:

TensorFlow \- Open source, Python

Tweety \- Open source, Java

Linas Vepstas' site lists a few others

I just found these quickly, so I don't know what application they'll have to you without more specifics about the language you plan on coding in and your coding philosophy and practices.

**What key issues do you think I overlooked?**

The complexity of this level of AI. You can't just tell a program to learn and create, you have to give it a ton of information and guidelines. It takes months of experimenting to find things that work well, and even then, your AI can mess up. If you're not familiar with the hard science and math behind AI, I wouldn't suggest you go about trying to implement one in your game unless you really know what you're doing.
> 1 votes

---
Tags: game-design, ai, text-based, bot
---


# Question
Title: Is it OK to use 6-7k texture map in Unity?
I want to unwrap all my car into one texture (interier, wheels and e.t.c), so for better quality i need to use one big 7k texture. Is it OK or the better choice is to make smaller ones for groups ?

# Answer
> 4 votes
Going by WebGL Caps it looks like 4k textures are a very safe bet (which is why everyone is using them) but 8k textures still have a ways to go.

Ideally you'll want to have a 4k fallback option if your users don't support 8k textures.

That being said, your car shouldn't need an 8k texture, it's likely that your UV mapping could use some optimization. Make sure all your important surfaces are normalized and unimportant surfaces can be half the scale of the other islands, or even less.

# Answer
> 3 votes
So long as the platform is able to handle the texture size for performance reasons it's better to use one big texture in virtually all cases instead of lots of little ones. So I would generally put the whole car on one texture. The only exception might be if there is a lot of chance for customization. IE change out the mags and tires, adding decals, stuff like that.

---
Tags: textures, performance, uv-mapping
---


title: setSize in Phaser.io

text:
# Question
Title: setSize in Phaser.io
so I've been troubleshooting for hours now. I am using the latest version of Phaser.io and I cannot get troubleshoot the errors. I am aware that it is related to

```
Phaser.Rectangle.contains(e.body, game.input.activePointer.x, game.input.activePointer.y);

```

and

```
shapesprite.body.setSize(30, 30, 0, 0);

```

If you would like me to put the entire project on my GitHub, I am more than happy to do so or upload it to my website. I have commented out the line above, and it somewhat works, but then I get errors pertaining to "frame". My sprite has 18 I guess sections (not sure what to call it) to read through.

Here is the sprite image. The left column is the unclicked state, and then right column is the clicked state

The entire Javascript code is:

```
gameObj.Game = function (game) {
    //step 1
    var myTime;
    var gameSeconds; //total game seconds
    var timerSeconds = "0"; //current timer in seconds
    var secondsLeft; //total game seconds - current timer second
    var points;
    var pointsShow;
};
var tile_size = 69;

gameObj.Game.prototype = {
    create: function () {
        var border = this.add.sprite(this.world.centerX, this.world.centerY, 'border');
        border.anchor.setTo(0.5, 0.5);

    var stroke = this.add.sprite(this.world.centerX + 30, this.world.centerX - 450, 'stroke');
    points = 0;
    gameObj.finalScore = points;
    var currentTarg = this.add.sprite(this.world.centerX + 200, this.world.centerX - 125, 'currenttarget');

    this.shapes = this.add.group();
    this.shapes.createMultiple(36, 'shapesprite');

    this.shapes.setAll('inputEnabled', true);
    this.shapes.setAll('input.useHandCursor', true);

    var progressbackground = this.add.sprite(this.world.centerX + 90, this.world.centerX - 380, 'progressbg');

    var myPercentStyle = {
        font: "400 24px Architects Daughter",
        fill: "#000",
        align: "center"
    };
    pointsShow = this.add.text(this.world.centerX + 195, this.world.centerX - 300, points + '%', myPercentStyle);

    var myProgress = "Progress of \nShape Painting"
    var myProgressStyle = {
        font: "400 18px Architects Daughter",
        fill: "#000",
        align: "center"
    };
    var myProgressShow = this.add.text(this.world.centerX + 160, this.world.centerX - 360, myProgress, myProgressStyle);

    var currentTargText = "Mix colors and make a:"
    var currentTargStyle = {
        font: "400 18px Architects Daughter",
        fill: "#000",
        align: "center"
    };
    var currentTargShow = this.add.text(this.world.centerX + 135, this.world.centerX - 220, currentTargText, currentTargStyle);

    var targetBg = this.add.sprite(this.world.centerX + 140, this.world.centerX - 190, 'targetbg');

    var timerbackground = this.add.sprite(this.world.centerX + 90, this.world.centerY + 120, 'timerbg');

    var myTimeText = "Time until Art Show:";
    var myTimeTextStyle = {
        font: "400 24px Architects Daughter",
        fill: "#000",
        align: "center"
    };
    var myTimeShow = this.add.text(this.world.centerX + 110, this.world.centerX + 35, myTimeText, myTimeTextStyle);

    var myTime = "2:00"
    var myTimeStyle = {
        font: "400 35px Architects Daughter",
        fill: "#000",
        align: "center"
    };

    myTimerShow = this.add.text(this.world.centerX + 190, this.world.centerX + 70, myTime, myTimeStyle);

    tmpWinnerBtn = this.add.button(100, 200, 'btn_winner', this.winnerFun, this, 1, 0, 2);
    tmpWinnerBtn.anchor.setTo(0.5, 0.5);

    tmpLoserBtn = this.add.button(200, 200, 'btn_loser', this.loserFun, this, 1, 0, 2);
    tmpLoserBtn.anchor.setTo(0.5, 0.5);
    //timevars
    tmpPointsBtn = this.add.button(300, 100, 'points_btn', this.pointsIncrease, this, 1, 0, 2);

    gameSeconds = 120;
    timerSeconds = 0;
    secondsLeft = 0;

    //create timer object
    timerObj = this.game.time.create(false);
    //set a timer event to occur every 1 second
    timerObj.loop(1000, this.updateTimer, this);
    //start the timer running
    timerObj.start();

    //        this.combo_s = this.game.add.audio('combo');

    this.clicked = false;
    this.count = 0;
    this.moves = 0;
    this.type = -1;
    this.deleted_shapes = [];
    this.pos_i = -1;
    this.pos_j = -1;
    this.offset_x = 120;
    this.offset_y = 150;
    this.next_time = 0;
    score = 0;
    //this.width=69;
    this.build_world();
},

update: function () {

    this.shapes.forEachAlive(function (e) {
        if (e.scale.x == 2) e.kill();
    }, this);

    if (game.input.activePointer.isDown && game.time.now > this.next_time) {
        this.clicked = true;
        this.try_select_a_shapesp();
    }

    if (game.input.activePointer.isUp && this.clicked) {
        if (this.count > 1) {
            this.remove_selected_shapes();
            this.move_shapes_down();
            this.add_missing_shapes();

        } else
            this.unselect_all_shapes();

        //this.next_time = game.time.now + 300;
        this.count = 0;
        this.clicked = false;
        this.type = -1;
        this.pos_i = -1;
        this.pos_j = -1;
    }
},
build_world: function () {
    for (var i = 0; i < 6; i++)
        for (var j = 0; j < 6; j++)
            this.add_shapesp(i, j, true);
},
add_shapesp: function (i, j, type) {
    var shapesprite = this.shapes.getFirstExists(false);

    var r = rand(3);
    if (r == 1) shapesprite.frame = 2;
    else if (r == 3) shapesprite.frame = 6;
    else if (r == 2) shapesprite.frame = 4;
    //        else if (r == 2) shapesprite.frame = 4;
    //        else if (r == 3) shapesprite.frame = 6;

    //        else if (r == 4) shapesprite.frame = 8;
    //        else if (r == 5) shapesprite.frame = 10;
    //        //        else if (r == 6) shapesprite.frame = 12;
    //        else if (r == 7) shapesprite.frame = 14;
    //        //        else if (r == 8) shapesprite.frame = 16;
    //        else if (r == 9) shapesprite.frame = 18;
    //        //        else if (r == 10) shapesprite.frame = 20;
    //        else if (r == 11) shapesprite.frame = 22;
    //        //        else if (r == 12) shapesprite.frame = 24;
    //        else if (r == 13) shapesprite.frame = 26;
    //        else if (r == 14) shapesprite.frame = 28;
    //        //        else if (r == 15) shapesprite.frame = 30;
    //        else if (r == 16) shapesprite.frame = 32;
    //        else if (r == 17) shapesprite.frame = 34;
    //        else if (r == 18) shapesprite.frame = 36;

    shapesprite.anchor.setTo(0.5, 0.5);
    shapesprite.selected = false;
    shapesprite.pos_i = i;
    shapesprite.pos_j = j;
    shapesprite.move_y = 0;
    shapesprite.move_x = 1;

    shapesprite.body.setSize(30, 30, 0, 0);
    shapesprite.alpha = 1;
    shapesprite.scale.setTo(5, 1);
    shapesprite.alive2 = true;
    shapesprite.reset(this.offset_x + j * tile_size, this.offset_y + i * tile_size);

    if (type)
        this.game.add.tween(shapesprite.scale).delay(j * 100 + 1).to({
            x: 1,
            y: 1
        }, 400).start();
    else
        this.game.add.tween(shapesprite.scale).delay(400).to({
            x: 1,
            y: 1
        }, 400).start();
},

try_select_a_shapesp: function (e) {
    this.shapes.forEachAlive(function (e) {
        var bool = Phaser.Rectangle.contains(e.body, game.input.activePointer.x, game.input.activePointer.y);

        if (e.selected || !bool) {
            //console.log('hi');
            return;
        }

        if (this.type == -1)
            this.type = e.frame;

        if (this.type == e.frame && this.in_range(e))
            this.select_a_shapesp(e);
        else
            this.unselect_all_shapes();
    }, this);
},

select_a_shapesp: function (e) {

    e.selected = true;
    e.frame += 1;
    this.count += 1;
    this.pos_j = e.pos_j;
    this.pos_i = e.pos_i;
    // this.increase_bar();
},

remove_selected_shapes: function (e) {
    this.shapes.forEachAlive(function (e) {
        if (!e.selected)
            return;

        this.game.add.tween(e.scale).to({
            x: 2,
            y: 2
        }, 300).start();
        this.game.add.tween(e).to({
            alpha: 0
        }, 300).start();
        this.deleted_shapes.push({
            i: e.pos_i,
            j: e.pos_j
        });
        e.alive2 = false;
    }, this);
},

unselect_all_shapes: function () {
    this.count = 0;
    this.shapes.forEachAlive(function (e) {
        if (e.selected) {
            e.selected = false;
            e.frame -= 1;
        }
    }, this);
    this.clear_bar();
},

move_shapes_down: function () {
    for (var i = 0; i < this.deleted_shapes.length; i++) {
        var tmp_i = this.deleted_shapes[i].i;
        var tmp_j = this.deleted_shapes[i].j;

        this.shapes.forEachAlive(function (e) {
            if (!e.selected && e.pos_j == tmp_j && e.pos_i < tmp_i)
                e.move_y += tile_size;
        }, this);
    }

    this.shapes.forEachAlive(function (e) {
        if (e.move_y == 0)
            return;

        var coef = e.move_y / tile_size;
        e.pos_i += coef;
        this.add.tween(e).delay(100).to({
            y: e.y + e.move_y
        }, 100 * coef).start();
        e.move_y = 0;
    }, this);

    this.deleted_shapes = [];
},

add_missing_shapes: function () {
    var min = [6, 6, 6, 6, 6, 6];

    this.shapes.forEachAlive(function (e) {
        if (e.pos_i < min[e.pos_j] && e.alive2)
            min[e.pos_j] = e.pos_i;
    }, this);

    for (var i = 0; i < 6; i++)
        for (var j = 0; j < min[i]; j++)
            this.add_shapesp(j, i, false);
},

update_score_and_labels: function () {

    this.clear_bar();
    this.game.state.start('End');
},

in_range: function (d) {
    if (this.pos_j == -1) return true;

    return (this.pos_j - 1 == d.pos_j && this.pos_i == d.pos_i) ||
        (this.pos_j + 1 == d.pos_j && this.pos_i == d.pos_i) ||
        (this.pos_j == d.pos_j && this.pos_i - 1 == d.pos_i) ||
        (this.pos_j == d.pos_j && this.pos_i + 1 == d.pos_i);
},
clear_bar: function () {
    this.game.add.tween(this.progress).to({

    }, 300).start();
},

add_tuto: function () {
    this.tuto = this.game.add.button(0, 0, 'tuto', this.remove_tuto, this);
},

updateTimer: function () {
    //console.log('hola');
    timerSeconds++;

    if (timerSeconds <= gameSeconds) {
        secondsLeft = gameSeconds - timerSeconds;
        //
        displayMin = Math.floor(secondsLeft / 60) % 60;
        displaySec = Math.floor(secondsLeft) % 60;
        //
        if (displayMin < 10) {
            displayMin = "" + displayMin;
        }
        if (displaySec < 10) {
            displaySec = "0" + displaySec;
        }
        myTimerShow.setText(displayMin + ":" + displaySec);
    } else {
        timerSeconds = 0;
        this.loserFun();
    }
},
pointsIncrease: function () {
    //console.log("increase");
    gameObj.finalScore += 10;
    points = gameObj.finalScore;
    pointsShow.setText(points + "%");

    if (points == 100) {
        this.game.state.start('Winner');
    }
},
winnerFun: function () {
    gameObj.finalTime = timerSeconds;
    this.state.start('Winner');
},
loserFun: function () {
    gameObj.finalTime = timerSeconds;
    this.state.start('Loser');
}

```

};

Oh, and the error I get is

```
Game.js:195 Uncaught TypeError: Cannot read property 'setSize' of null

```

Yes, I know what it means, but I cannot seem to figure out how to get rid of it.

Thank you!

# Answer
It doesn't look like you're initializing the physics anywhere.

If you're trying to set attributes on the 'body', the body will be null unless you've initialized a physics engine on the sprite. Do this with something like:

```
game.physics.startSystem(Phaser.Physics.ARCADE);
game.physics.enable(shapesprite, Phaser.Physics.ARCADE);

```

But my guess is that you aren't trying to set the size of the body (what collides with things, but you don't see).

It looks like you're trying to set the size of the sprite? If that's the case, try changing the size of the sprite by scaling the image with:

```
shapesprite.scale.setTo(xScale, yScale)

```
> 1 votes

---
Tags: javascript, phaser
---


title: 2D Driving Game with Unity

text:
# Question
Title: 2D Driving Game with Unity
I'm trying to make a 2D car driving game in Unity and I'm having problems with my code.

I am able to move forward,backward,turn left/right using arrow key from my present code

```
using UnityEngine;
using System.Collections;

public class CarControll : MonoBehaviour {

// Use this for initialization
float speedForce = 15f;
float torqueForce = -200f;
float driftFactorSticky = 0.9f;
float driftFactorSlippy = 1;
float maxStickyVelocity = 2.5f;
float minSlippyVelocity = 1.5f;

bool move=false;
public bool forwardArrow=false;
public bool backwardArrow=false;

public bool rightTurn=false;
// Use this for initialization
void Start () {

}

void Update() {

    move=true;
}

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

    Rigidbody2D rb = GetComponent<Rigidbody2D>();

    float driftFactor = driftFactorSticky;
    if(RightVelocity().magnitude > maxStickyVelocity) {
        driftFactor = driftFactorSlippy;
    }

    rb.velocity = ForwardVelocity() + RightVelocity()*driftFactor;

    if( Input.GetButton("Accelerate") || Input.GetButtonDown("Forward") || Input.GetKeyDown(KeyCode.UpArrow)) {
        Debug.Log ("Uparrow....................................................");
        rb.AddForce( transform.up * 20);

    }

    if( forwardArrow==true) {

        rb.AddForce(transform.up*0.5f);
    }

    if(backwardArrow==true) {

    rb.AddForce( transform.up * -speedForce/25f );
    }

    if(Input.GetButton("Brakes") || Input.GetButton("Backword") || Input.GetKeyDown(KeyCode.DownArrow)) {

        rb.AddForce( transform.up * -speedForce/2f );
    }

        float tf = Mathf.Lerp (0, torqueForce, rb.velocity.magnitude / 2);
        rb.angularVelocity = Input.GetAxis ("Horizontal") * tf;

}

Vector2 ForwardVelocity() {

    return transform.up * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.up );
}

Vector2 RightVelocity() {

    return transform.right * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.right );
}

public void MoveForward()  //forward button
{
    forwardArrow = true;
    backwardArrow = false;
}

public void MoveBackward() backward button
{
    backwardArrow = true;
    forwardArrow = false;
}

public void RightTurn()  //right button
{

    rightTurn = true;
}

```

}

I have added four button(Forward,backward,right,left).Now I need to move the car using this button. The car is moving Forward,backward using the button but when Press the right/left button the car is not Turing left/right while move.But its working perfectly on key press.Can anyboady help solving this issue

# Answer
> -1 votes
First a small side note: you may have a typo

```

if(Input.GetButton("Brakes") || Input.GetButton("Backword")

```

With "Backword" did you mean "Backward"?

---

Since I don't find any Input.GetButton("left") or Input.GetButton("right") I assume that you use Input.GetAxis("Horizontal") for left and right.

In that case I guess you have to map your buttons to controll the horizontal axis. The keyboard keys are already mapped to control the horizontal axis. In the menu of Unity take a look into Edit / Project Settings / Input. There are the mappings.

I don't know if you can map them to UI buttons though. I haven't worked a lot with the UI so far. You will need something like if UI button down set a variable (e.g. moveLeft) to true and if if UI button is released set the variable (e.g. moveLeft) to false and change your code in that way.

This question recommends adding EventTriggers to the button to do that.

---
Tags: unity, c#, gui, control, car
---


# Question
Title: IsoSurface Normals\Texture Coords Problems(DX11\SharpDX)
Hi and thanks for your time!

So over the past few days I have been playing with isosurface construction from volume textures, I have it running on the cpu and all is well from a "just got it working" stand point eg. surface reconstruction works and I have my really cool voxel mesh drawing.

I have based my code(converted to VB.net) on Paul Bourke's work here: Polygonising a scalar field and like I said it works well apart from the fact that my normals are wrong and I have these strange fully black on both sides triangles, I think I'm doing my normals wrong but the way they are now is the beast I can get, I tried a few ways to build the normals and this one is the only way I could get smooth normals.

Here you can see how my normals are wrong, green should be up, gray\dark should be unlit and the hay'ish colour is the lit side.

I have tried to flip and invert them but as you can see they are not wrong all the same way.

HLSL Normals 1st try:

```
float3x3 cotangent_frame(float3 N, float3 p, float2 uv)

// get edge vectors of the pixel triangle
float3 dp1 = ddx(p);
float3 dp2 = ddy(p);
float2 duv1 = ddx(uv);
float2 duv2 = ddy(uv);

// solve the linear system
float3 dp2perp = cross(dp2, N);
float3 dp1perp = cross(N, dp1);
float3 T = dp2perp * duv1.x + dp1perp * duv2.x;
float3 B = dp2perp * duv1.y + dp1perp * duv2.y;

// construct a scale-invariant frame
float invmax =   -sqrt(max(dot(T, T), dot(B, B)));
return float3x3(T * invmax, B * invmax, N);

```

HLSL Normals 2nd try:

```
NormalData CalcWS_Normal(float2 WS_TexCoord, float3 WS_Pos)

NormalData dout;

float3 dp1 = ddx(WS_Pos);
float3 dp2 = ddy(WS_Pos);
float2 duv1 = ddx(WS_TexCoord);
float2 duv2 = ddy(WS_TexCoord);

float3x3 M = float3x3(dp1, dp2, cross(dp1, dp2));
float2x3 inverseM = float2x3(cross(M[1], M[2]), cross(M[2], M[0]));

float3 t = mul(float2(duv1.x, duv2.x), inverseM);
float3 b = mul(float2(duv1.y, duv2.y), inverseM);
float3 normal = normalize(cross(normalize(b), normalize(t)));

dout.Normal = normal;
dout.Tang = t;
dout.BiTang = b;

return dout;

```

Heres is how I'm doing it now, takes a vertex and then samples the volume texture

VB.net

```
   Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Single) As Vector3
    Dim rfNormal As Vector3
    rfNormal.X = fSample1(fX - fScale, fY, fZ) - fSample1(fX + fScale, fY, fZ)
    rfNormal.Y = fSample1(fX, fY - fScale, fZ) - fSample1(fX, fY + fScale, fZ)
    rfNormal.Z = fSample1(fX, fY, fZ - fScale) - fSample1(fX, fY, fZ + fScale)
    Return Vector3.Normalize(rfNormal)
End Function

Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Vector3) As Vector3
    Dim rfNormal As Vector3
    rfNormal.X = fSample1(fX - fScale.X, fY, fZ) - fSample1(fX + fScale.X, fY, fZ)
    rfNormal.Y = fSample1(fX, fY - fScale.Y, fZ) - fSample1(fX, fY + fScale.Y, fZ)
    rfNormal.Z = fSample1(fX, fY, fZ - fScale.Z) - fSample1(fX, fY, fZ + fScale.Z)
    Return Vector3.Normalize(rfNormal)
End Function

```

Volume sampling code:

VB.net

```
Public Function GetVolumeData(_pos As Vector3) As Half
    Dim x2 As Single = Math.Abs((_pos.X / CellsPerPatch * 32) Mod mWidth)
    Dim y2 As Single = Math.Abs((_pos.Y / CellsPerPatch * 8) Mod mDepth)
    Dim z2 As Single = Math.Abs((_pos.Z / CellsPerPatch * 32) Mod mHeight)

    Return mScalars(CInt(Math.Truncate(x2)) + (CInt(Math.Truncate(z2)) * mWidth) + (CInt(Math.Truncate(y2) * mWidth * mWidth)))
End Function

```

The rest of the isosurface construction code is just a copy-\> convert-\> paste of Paul Bourke's c code.

Just to makes sure everyone knows what I'm asking: Can anyone tell me what I'm doing wrong? Is it a problem with my normals or the isosurface stuffs or both?

All of the above is just so u have some context, I'm happy to post more code if ppl need to see it

\[EDIT\]: Black squares come from having no depth info at that point so my deferred render hates those spots, this is leading back to maybe a problem with the surface reconstruction? But why its only happening in those spots, one would think that it would happen everywhere?

# Answer
> 0 votes
I didn't sleep last night, turns out I was doing it all wrong.

Ill list my !#@! up's then show you how it looks now.

Strange looking mesh:

a). Marching cubes in world space and trying to scale the world space voxel positons to pixels in the volume texture. Just march over the volume per pixel and scale in the vertex shader with a world matrix.

b). Have an index buffer now too.

Black triangles:

Iso value to big, I had it at 23 but now have it at 0.001.

Normals wrong:

a). Pick the right culling state and don't use cullnone. b). Once I changed the way I was marching I was able to get the vGetNormal function to work and convert face normal to vertex normal(still a bit messy).

As you can see its looking much better some faces are still a bit funky and I need to redo my lighting because its been set for just height based terrain.

The dark green comes from my SH lighting that is baked for my old terrain so once I re generate that it should look a bit nicer

I also added triplanar mapping so it looks a bit nicer than having just rocks everywhere and by fixing all that I got my mem usage down by heaps and my isosurface build time down to 5sec using threads.

---
Tags: directx11, sharpdx, normals
---


# Question
Title: Unity UI issue trying to make a button work while held down
Pretty simple, have a rotate up button and I want it to rotate while held down.

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class cannonController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public Vector3  force;
Rigidbody2D rg;
Vector3 up;
public bool pointerDown = true;
Vector3 down;
// Use this for initialization
void Start () {
    rg = GetComponent<Rigidbody2D>();
    up = new Vector3(0f, 0f, 20f);
    down = new Vector3(0f, 0f, -3f);
}

/// <summary>
///  all of the rotation stuff
/// </summary>
    public void RotateSTOP()
    {
        rg.transform.Rotate(Vector3.zero);
    }
    public void RotateDown()
    {
    rg.transform.Rotate(down);
    }
    public void RotateUp()
    {
    while(pointerDown == true)
    {
        rg.transform.Rotate(up, Time.deltaTime);
    }

    }
/// <summary>
/// sets pointerDown to check if button is held down
/// </summary>
/// <param name="eventData">Event data.</param>
public void OnPointerDown(PointerEventData eventData)
{
    pointerDown = true;
}

public void OnPointerUp(PointerEventData eventData)
{
    pointerDown = false;
}

```

}

# Answer
> 1 votes
Well, all the above answers were already correct so far but here is my example with code. It's a basic but working implementation. You will have to adjust it to your needs.

For the sake of completeness here is how (someone needs) to configure the buttons

* attach the script to the canon
* First create two ui buttons
* add an Event Trigger component on each
* map On Pointer Down and On Pointer Up of each button to call the according methods on the bottom of the script

public class CanonController : MonoBehaviour {

```
public GameObject goToRotate;

public Vector3 up = new Vector3(0f, 0f, 20f);
public Vector3 down = new Vector3(0f, 0f, -20f);

// public just for the reason to start it within the inspector
public bool isUpDown;
public bool isDownDown;

// Use this for initialization
void Start () {
    isUpDown = false;
    isDownDown = false;

    if (goToRotate == null) goToRotate = this.gameObject;
}

void Update () {
    // I leave it up to you to decide between Update and FixedUpdate
    if (isUpDown) goToRotate.transform.Rotate(up * Time.deltaTime);
    if (isDownDown) goToRotate.transform.Rotate(down * Time.deltaTime);
}

//those methods are called from the EventTrigger component of the button up and button down
//use Pointer Up and Pointer Down and match them accordingly
public void UpDown()  { isUpDown = true; }
public void UpUp()    { isUpDown = false; }
public void DownUp()   { isDownDown = false; }
public void DownDown() { isDownDown = true; }

```

}

and it should rotate

if both buttons are pressed at the same time it gets rotated twice and if up and down are the exact opposite it should end up with zero rotation.

---

A small addition to the code given by you

```

    public void RotateUp()
    {
        while(pointerDown == true)
        {
            rg.transform.Rotate(up, Time.deltaTime);
        }
    }

```

This can lead into an (game freezing) endless loop if you would call it in OnClick since there is no way single threaded Unity could set pointerDown to false somewhere else.

# Answer
> 0 votes
You need to call the methods to make them work, simply putting them in assembly not helps.

```
void Update()
{
    if(pointerDown == true)
    {
        rg.transform.Rotate(up, Time.deltaTime);
    }
}

```

# Answer
> 0 votes
you could try something like this

```
void FixedUpdate()
{
    if(pointerDown == true)
    {
        rg.transform.Rotate(up, Time.deltaTime);
    }
    else
    {
        rg.transform.Rotate(down, Time.deltaTime);
    }
    rg.transform.rotation = Mathf.Clamp(rg.transform.rotation, down, up);
}

```

in this way the cnnon should rotate up while helding the button and down when button is released.

---
Tags: 2d, unity, ui-design
---


title: Money in different platforms

text:
# Question
Title: Money in different platforms
So first of all, let me start off by saying that I am not in this to make money as of right now. I'm a novice - however I would like (in the frture) to be able to earn some extra cash on the side with my games.

I have several ideas for what my first game could be and then I started considering the platform on which my game should run.

So I started thinking

iOS & Android mobile devices already have a built-in store that everyone uses. This means that even if my game doesn't get a lot of attention (and doesn't reach the highest position on the market) everyone would still be able to find my game on the same platform.

How is this possible with games made for web or even desktop?

Are the chances of making money of web and desktop as big as on the mobile market?

# Answer
While this could potentially be largely opinion-based, I would say that it seems unlikely that web games are true money-makers, unless you make a Facebook app that rakes in cash ala Farmville or something similar. Desktop can, especially on a platform like Steam or through a marketplace like GOG.

Consoles probably get the next highest grossing, supposing the game is actually decent.

Mobile - it's a tough gig. There is a ton of cruft on mobile stores because of the accessibility. However, if you do actually get noticed, by the store itself (moved to the front page) or by gaming news outlets, you can stand to make quite the pretty penny from mobile games. It really should be fresh and new, even if it's incredibly simple (look at the Flappy Bird phenomenon). Puzzle games seem to be doing really well on mobile these days.
> 1 votes

---
Tags: marketing, platform
---


# Question
Title: BRDF and Spherical coordinate in ray tracing
I developed a ray tracer that use standard phong/blinn phong lighting model. Now I'm modifying it to support physically based rendering, so I'm implementing various BRDF models. At the moment I'm focused on Oren-Nayar and Torrance-Sparrow model. Each one of these is based on spherical coordinates used to express incident wi and outgoing wo light direction.

**My question is: which way is the right one convert wi and wo from cartesian coordinate to spherical coordinate?**

I'm applying the standard formula reported here https://en.wikipedia.org/wiki/Spherical\_coordinate\_system#Coordinate\_system\_conversions but I'm not sure I'm doing the right thing, **because my vector are not with tail at the origin of the cartesian coordinate system, but are centered on the intersection point of the ray with the object.**

Here you can find my current implementation:

Can anyone help me giving an explanation of the correct way to convert the wi and wo vector from cartesian to spherical coordinate?

**UPDATE**

I copy here the relevant part of code:

spherical coordinate calculation

```
float Vector3D::sphericalTheta() const {

    float sphericalTheta = acosf(Utils::clamp(y, -1.f, 1.f));

    return sphericalTheta;
}

float Vector3D::sphericalPhi() const {

    float phi = atan2f(z, x);

    return (phi < 0.f) ? phi + 2.f * M_PI : phi;
}

```

Oren Nayar

```
OrenNayar::OrenNayar(Spectrum<constant::spectrumSamples> reflectanceSpectrum, float degree) : reflectanceSpectrum{reflectanceSpectrum} {

    float sigma = Utils::degreeToRadian(degree);
    float sigmaPowerTwo = sigma * sigma;

    A = 1.0f - (sigmaPowerTwo / 2.0f * (sigmaPowerTwo + 0.33f));
    B = 0.45f * sigmaPowerTwo / (sigmaPowerTwo + 0.09f);
};

Spectrum<constant::spectrumSamples> OrenNayar::f(const Vector3D& wi, const Vector3D& wo, const Intersection* intersection) const {

    float thetaI = wi.sphericalTheta();
    float phiI = wi.sphericalPhi();

    float thetaO = wo.sphericalTheta();
    float phiO = wo.sphericalPhi();

    float alpha = std::fmaxf(thetaI, thetaO);
    float beta = std::fminf(thetaI, thetaO);

    Spectrum<constant::spectrumSamples> orenNayar = reflectanceSpectrum * constant::inversePi * (A + B * std::fmaxf(0, cosf(phiI - phiO) * sinf(alpha) * tanf(beta)));

    return orenNayar;
}

```

Torrance-Sparrow

```
float TorranceSparrow::G(const Vector3D& wi, const Vector3D& wo, const Vector3D& wh, const Intersection* intersection) const {

    Vector3D normal = intersection->normal;
    normal.normalize();

    float normalDotWh = fabsf(normal.dot(wh));
    float normalDotWo = fabsf(normal.dot(wo));
    float normalDotWi = fabsf(normal.dot(wi));
    float woDotWh = fabsf(wo.dot(wh));

    float G = fminf(1.0f, std::fminf((2.0f * normalDotWh * normalDotWo)/woDotWh, (2.0f * normalDotWh * normalDotWi)/woDotWh));

    return G;
}

float TorranceSparrow::D(const Vector3D& wh, const Intersection* intersection) const {

    Vector3D normal = intersection->normal;
    normal.normalize();

    float cosThetaH = fabsf(wh.dot(normal));

    float Dd = (exponent + 2) * constant::inverseTwoPi * powf(cosThetaH, exponent);

    return Dd;
}

Spectrum<constant::spectrumSamples> TorranceSparrow::f(const Vector3D& wi, const Vector3D& wo, const Intersection* intersection) const {

    Vector3D normal = intersection->normal;
    normal.normalize();

    float thetaI = wi.sphericalTheta();
    float thetaO = wo.sphericalTheta();

    float cosThetaO = fabsf(cosf(thetaO));
    float cosThetaI = fabsf(cosf(thetaI));

    if(cosThetaI == 0 || cosThetaO == 0) {

        return reflectanceSpectrum * 0.0f;
    }

    Vector3D wh = (wi + wo);
    wh.normalize();

    float cosThetaH = wi.dot(wh);

    float F = Fresnel::dieletricFresnel(cosThetaH, refractiveIndex);
    float g = G(wi, wo, wh, intersection);
    float d = D(wh, intersection);

    printf("f %f g %f d %f \n", F, g, d);
    printf("result %f \n", ((d * g * F) / (4.0f * cosThetaI * cosThetaO)));

    Spectrum<constant::spectrumSamples> torranceSparrow = reflectanceSpectrum * ((d * g * F) / (4.0f * cosThetaI * cosThetaO));

    return torranceSparrow;
}

```

**UPDATE 2**

After some search I found this implementation of Oren-Nayar BRDF.

In the implementation above theta for wi and wo is obtained simply doing arccos(wo.dotProduct(Normal)) and arccos(wi.dotProduct(Normal)). This seems reasonable to me, as we can use the normal of the intersection point as the zenith direction for our spherical coordinate system and do the calculation. The calculation of gamma = cos(phi\_wi - phi\_wo) do some sort of projection of wi and wo on what it calls "tangent space". Assuming everything is correct in this implementation, can i just use the formulas |View - Normal x (View.dotProduct(Normal))| and |Light - Normal x (Light.dotProduct(Normal))| to obtain the phi coordinate (instead of using arctan("something"))?

# Answer
> 2 votes
It's actually better **not** to use spherical coordinates (or any angles for that matter) to implement BRDF's, but rather work straight in Cartesian coordinate system and use cosine of the angle between vectors, which is plain dot product between unit vectors as you know. This is both more robust and efficient.

For Oren-Nayar you may think you have to use angles (due to min/max of the angles), but you can simply implement the BRDF straight in Cartesian space: https://fgiesen.wordpress.com/2010/10/21/finish-your-derivations-please

For Torrance-Sparrow or Cook-Torrance microfacet BRDF's you don't need to use spherical coordinates either. In these BRDF's the angle is passed to a trigonometric (usually cosine) function in D/F/G terms & the BRDF denominator, so you can use dot product straight or trigonometric identities without going through spherical coordinates.

# Answer
> 1 votes
You can specify a coordinate system given the normal N and another vector. We'll choose wi. So any vector that has the same direction as wi when projected onto the tangent plane will have an azimuth of 0

First, we project wi on the tangent plane: (assuming wi is already normalized)

```
wit = normalize(wi - N * dot(wi, N))

```

now, we can do the same with wo:

```
wot = normalize(wo - N * dot(wo, N))

```

Now, wit and wot lie both on a plane which is orthogonal to N, and tangent to the point of intersection.

We can compute the angle between the two now:

```
azimuth = arcos ( dot(wit, wot) )

```

Which is really the azimuth of wot with respect to wit when projected on the tangent plane.

# Answer
> 0 votes
If you know the intersection point, and the point of origin, wouldn't it just be a question of subtracting one from the other so you get the result as if it were from the origin?

If you don't believe the result, and want to get there through the long way, you can also get the rotation transform to get from one point to another via a LookAt matrix, and then decomposing it to get the rotational component. You can also get a quaternion from it if you want.

The results are equal. The proof is a bit long, but not complicated, and is left up to the reader.

---
Tags: coordinates, raytracing
---


title: Sprite rotation LibGDX

text:
# Question
Title: Sprite rotation LibGDX
I'am using the current mouse position to aim the player sprite, but I am not getting the best results. I want my sprite to have the direction pointed wherever my cursor is in the screen.

Here's my code: My update method

```
public void update(float dt){
    time += dt;
    float yInput = (Gdx.graphics.getHeight() - Gdx.input.getY());
    vec.set(Gdx.input.getX() - position.x, yInput - position.y).nor();
    //position is a Vector2 update sprite coordinates
    position.x += vec.x * 15f;
    position.y += vec.y * 15f;
}

```

and here's my draw method

```
public void draw(){
    batch.begin();
    sprite.setPosition(position.x - sprite.getWidth()/2, position.y - sprite.getHeight()/2);

    float xInput = Gdx.input.getX();
    float yInput = (Gdx.graphics.getHeight() - Gdx.input.getY());

    float angle = MathUtils.radiansToDegrees * MathUtils.atan2(yInput - position.y, xInput - position.x);

    if(angle < 0){
        angle += 360;
    }
    sprite.rotate(angle);

    sprite.draw(batch);
    batch.end();
}

```

So what's wrong? why I get bad results?

# Answer
> 3 votes
This may not be the answer but, instead of using

```
sprite.rotate(float angle);

```

use:

```
sprite.setRotation(float angle);

```

Hope this helps! :D

# Answer
> 1 votes
```
sprite.rotate(float degrees);

```

and

```
sprite.setRotation(float degrees);

```

is different methods, "sprite.rotate" **is adding degrees to current "angle"**, "sprite.setRotation" **is set** given degrees to the angle.

# Answer
> 0 votes
You are rotating the sprite using an int, 0-360, instead of a float.

Try doing

sprite.setRotation(angle/360f);

---
Tags: java, libgdx, rotation
---


title: Making plane with quad

text:
# Question
Title: Making plane with quad
I'm a beginner Unity 3d developer. I want to keep quads one aside another touching each other and use that as a road for making an endless runner game. The problem is each of the quads have their own box collider thus the car bounces a little bit sometimes.

Is there any way to get those stuff connected with each other and make the whole thing behave like a single plane?

I know using a big box collider covering all the quads in the repeating unit is gonna work but I don't want to use that.

# Answer
> 1 votes
You might have these stutters with your car because of the collision update being to slow. You can try setting the collsion update mode on your car's rigidbody to continues dynamic or continues for smoother collision detection.

Another solution might be to not use the physics engine but instead make objects move in game code. In a infinite runner game like you are making now it might not be necessary to use the physics engine. Or at least not make the car move with physics and gravity.

---
Tags: unity, c#, terrain, joints
---


title: Checking if shapes will tessellate

text:
# Question
Title: Checking if shapes will tessellate
I'm trying to figure out where to start with getting code together to check if a shape tessellates.

An example:

Consider that the shapes cannot be rotated, just as-is. A 'compound' shape (as seen in the pic - second and third shapes) will have a series of co-ordinates that make them up.

Where could I begin to getting the computer to figure out if they can tessellate?

I'm using c# & unity. Thanks in advance.

# Answer
> 2 votes
Taken from the Tessellation entry of Wikipedia on 9/20/2016:

> No general rule has been found for determining if a given shape can tile the plane or not, which means there are many unsolved problems concerning tessellations. For example, the types of convex pentagon that can tile the plane remains an unsolved problem.

You code a generate & test type algorithm that applied various rotations, flips & translation to attempt to find a tessellation for a given polygon, but a failure to find a tessellation for the polygon wouldn't necessarily guarantee that one didn't exist.

Depending on what your overall goal is, you might appreciate knowing that it is possible to start with a known tessellating shape & algorithmically generate a new tessellating shape.

Given your restriction of using only translations, you can brute force the problem as follows:

* Enumerate your vertices in some order.
* Test the result of moving each vertex to every other unchecked vertex.
    + If the result does not overlap, label the move (see note 1) & save the result to a list called safe-moves.
* Examine all the combinations of entries (see note 2) from the safe-move as follows:
    + If the current move overlaps any previous move, it can't tessellate, so try the next combination (see note #3).
    + If none of the moves from the combination overlap, check to see if there is any unfilled space around the original shape.
    + If there is no unfilled space, you have a legal tessellation!
    + If there is empty space, try the next combination.

Notes:

1. Label the moves as pairs 'alphabetically'; i.e. if you had a square labeled clockwise from the upper left corner, & moved vertex 1 to vertex 3 (translated the shape south), it would give the safe move called (1,3)(2,4). Thus, you wouldn't need to later try to move vertex 2 to vertex 4 since it is already recorded in this move. Also, you know the reverse mapping of 3 to 1 is safe & could also add it to the list now. If you add reverse safe mode as you go, then you only need to check mapping a given vertex to higher number vertices as mappings to lower number will already have been accounted for.
2. If you have n # of vertices,I think you can you won't ever need a combination of more than 2n moves, but I haven't managed to prove that.
3. For example if you start with this shape:

The move combination (2,5)(2,6) gives the following result which overlaps & must be rejected:

The legal move combination for that shape happens to be: (1,2)(5,4)(6,3), (1,4), (1,5)(2,4), (2,1)(3,6)(4,5), (2,5), (4,1), (4,2)(5,1), (5,2)

---
Tags: unity, c#, mathematics, geometry, tessellation
---


# Question
Title: How to make WASD equivalent input on mobile in Unity?
I'm familiar with Unity 3d, but I haven't made phone games before.

I have already looked into the input manager to no evail. The problem is that I don't know how to make a WASD-like input on a phone with a touch screen.

How could I do it?

# Answer
> -1 votes
Check out this link to study up on joysticks in unity:

http://wiki.unity3d.com/index.php?title=Joystick

---
Tags: unity, android
---


# Question
Title: How to use the Windows Phone SDK Namespaces in my Unity project?
I'm developing a game with Unity and using C# as the language for the scripts. I want to use the Device Vibration in my Microsoft Phone which is easily available for Windows Phone Development in Visual Studio using the following:

```
using Windows.Phone.Devices.Notification;

```

And then calling the following method:

```
VibrationDevice testVibrationDevice = VibrationDevice.GetDefault();
testVibrationDevice.Vibrate(TimeSpan.FromSeconds(3));

```

The above works perfectly when I'm building a Windows Phone App from visual Studio. However i totally need to integrate the above functionality in my Unity game.

Any suggestions, workarounds, tips or even hacks would be really helpful. Thanks in advance.

# Answer
> 1 votes
You should write a plugin to use that method directly in Unity.

Here is how you can create any plugin for Windows Phone in Visual Studio for Unity.

You can write it in both C++ or C#. You will be writing a `Windows Phone Class Library` that will contain your native methods in it. Then you build some `.dll`files and bring those to Unity an put them in Asset\>Plugins\>WP directory. Then you can access those methods using namespace.

Be careful when selecting `.NET` version for `RealDLL` and `FakeDLL`.

**Tip**: In mobile games single vibration is mostly used. If you really don't need the time spanned vibration you can use Handheld.Vibrate().

---
Tags: unity, c#, visual-studio, windows-phone-8, microsoft
---


# Question
Title: Animation Starts Before KeyDown Event Even Happens?
Recently when I started working on my first animation transition, it has a bug were the transition will occur as soon as the game begins, even though I haven't pressed the key to activate the transition. I would really appreciate any help I can get on this so I can continue creating more animations. I will include my C# code and an image of the transition below. Thanks, Nova

```
using UnityEngine;
using System.Collections;

public class PlayerAC : MonoBehaviour
{
    private Animator anim;

    void Start ()
    {
        anim = GetComponent<Animator> ();
    }

    void Update () {

        if (Input.GetButton ("Fire1"))
        {
            anim.SetBool ("RunStright", true);
        }
        else
        {
            anim.SetBool ("RunStright", false);
        }
    }
}

```

# Answer
The default value of parameter RunStright is true, you can try unchecking it first before playing, i think this could help.

Edit 1: Added some images to clarify my answer

@nova nanite

> I don't believe so, but I did notice that when has exit time is checked it will run when I click it but, it will only work if I press the key before it reaches the duration line. When I have has exit time not checked it cause the main problem I stated in my question were it plays as soon as it reaches the duration line.

(Sorry I dont have the privilege to add comment yet)
It doesnt really work when you check the HasExitTime box !

Because when you have that option checked, though the condition of the transition is satifised it must wait until the current animation state finishes, so during the time when you have the first animation state running, the transition can't be activated, even if you want to activate it manually.
So what really happened is that at the moment when you pressed the button the animation was about to finish (i guess the first animation state lasts 1 second), that gave an impression that you activated the transition but no, really, even if you didn't press anything the transition would still occur anyway.
> 0 votes

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


# Question
Title: If raycast hit nothing my object stay at end of the ray?
How to make an object stay at end of the raycast if the ray hit nothing ?! Here is my script

```
using UnityEngine;
using System.Collections;

public class ray : MonoBehaviour {

public float howFar;
public Vector3 loaction;
public Transform spot_position;
public Vector3 loaction_air;

void Start() {

}

void FixedUpdate()  {
    Vector3 fwd = transform.TransformDirection(Vector3.forward);
    RaycastHit hit;

    if (Physics.Raycast(transform.position, fwd, out hit, 100)) {
        print("Ray hit something !");
        loaction = hit.point;
        howFar = hit.distance;
        spot_position.transform.position = hit.point;
    }
    else {
  //            howFar = ....
 //         spot_position.transform.position = ...
        print (" Nothing ");
    }

    loaction_air = new Vector3(spot_position.transform.position.x,spot_position.transform.position.y,spot_position.transform.position.z);
}

}

```

# Answer
> 1 votes
I think this should give you the desired effect:

```
if (Physics.Raycast(transform.position, fwd, out hit, 100)) {
    spot_position.transform.position = hit.point;
}
else {
    spot_position.transform.position = transform.position + fwd* 100;
}

```

Also, if you are new to Unity I think there are some helpful tips that you may not know yet.

1/ You can easily get the forward vector of the object with transform.forward.

2/ transform.position returns a new copy of object's position so just get position of object with transform.position and do what you want with that copy, the object's position remains unaffected.

3/ If you have the reference to the Transform component, then there is no need to refer to transform again, just use that reference as a Transform normally.

Lets simplify your code using those tips above:

```
using UnityEngine;
using System.Collections;

public class Ray : MonoBehaviour
{

    public float howFar;
    public Vector3 location;
    public Transform spotPosition;
    public Vector3 locationAir;

    void Start()
    {

    }

    void FixedUpdate()
    {
        var fwd = transform.forward;
        var distance = 100f;
        RaycastHit hit;
        if (Physics.Raycast(transform.position, fwd, out hit, distance )) {
            Debug.Log("Ray hit something !");
            location= hit.point;
            howFar = hit.distance;
            spotPosition.position = hit.point;
        } else
        {
            Debug.Log(" Nothing ");
            howFar = distance;
            spotPosition.position = transform.position + fwd* distance;
        }

        locationAir = spotPosition.position;
    }
}

```

# Answer
> 1 votes
To call the raycast you have to give the fuction the direction and distance parameters.

Just use this information, and add the normalized direction (will be already normalized if you are using forward) multiplyed by the distance to the object position:

`itemToMove.transform.position += transform.Forward.normalized * distance`

---
Tags: unity, raycasting
---


# Question
Title: Projectile movement around spheres of varying gravity
I found a game on the Internet called Sagittarius. This game is very fun, and I have a question: how can I make the arrow move like it does in this game? I know each sphere has a different gravity, but when I try to use this formula, it's not working as I expect=. Can any one help me resolve this problem? Thanks.

```
  public List<PlanetABC> p = new List<PlanetABC>() {
    new PlanetABC(){
        x = 0.91f,
        y = -1.28f,
        gravity = 5,
        r = 5
    },
    new PlanetABC(){
        x = 8.12f,
        y = -1.3f,
        gravity = 3,
        r = 10
    }
};
void Start () {

}
void Update () {
    float gravityOnX = 0;
    float gravityOnY = 0;
    foreach (var planet in p)
    {
        if (Vector2.Distance(g.transform.position, new Vector2(planet.x, planet.y)) > planet.r)
            continue;
        if (planet.x > g.transform.position.x)
            gravityOnX += planet.gravity;
        else gravityOnX -= planet.gravity;

        if (planet.y > g.transform.position.y)
            gravityOnY += planet.gravity;
        else gravityOnY -= planet.gravity;
    }

    if (currentGravityX > gravityOnX)
        currentGravityX -= Time.deltaTime;
    else currentGravityX += Time.deltaTime;

    if (currentGravityY > gravityOnY)
        currentGravityY -= Time.deltaTime;
    else currentGravityY += Time.deltaTime;

    Debug.Log(currentGravityX + "/" + currentGravityY);
    var DEG2RAD = Mathf.PI/180;
    float vx1 = Mathf.Cos(angle * DEG2RAD) * power ;
    float vy1 = Mathf.Sin(angle * DEG2RAD) * power;
    float y = (0.5f * currentGravityY * time + vy1) * time;
    float x = (0.5f * currentGravityX * time + vx1) * time;
    Vector3 pos = g.transform.position;
    pos.x = x;
    pos.y = y;
    g.transform.position = Vector3.Lerp(g.transform.position, pos, Time.deltaTime);
    time += Time.deltaTime;
}

```

Here is the game: https://gprosser.itch.io/sagittarius

# Answer
Your method of calculating gravity is unusual. Is there a particular reason you've structured it this way?

A conventional gravity with inverse square falloff would look something like this...

```
// We're applying physics forces,
// so for consistency we should do this at a fixed timestep:
void FixedUpdate()
{
    // Initialize our acceleration to a zero vector:
    Vector2 totalAcceleration = Vector2.zero;

    foreach (var planet in p)
    {
        // Construct an arrow from the projectile to the planet center.
        Vector2 offset = planet.position - this.transform.position;
        Vector2 direction = offset.normalized;

        // Get the distance between the projectile and the planet.
        float distance = Vector2.dot(direction, offset);

        // Accumulate acceleration in the direction toward the planet,
        // with strength proportionate to the inverse square of the distance.
        totalAcceleration += direction * planet.gravity / (distance * distance);
    }

    // Apply the acceleration.
    // (f = ma, so we multiply by mass to convert to a force)
    rigidbody2D.AddForce(totalAcceleration * rigidbody2D.mass, ForceMode.Force);
}

```

You can integrate these forces yourself if you like, or course. But the built-in physics systems are already made for doing just this sort of work efficiently and stably, so it's not a bad idea to leverage that existing tech.

The major differences from your version are:

* gravity falls off using an inverse square law, as it does in real-world physics
* planets have no outer radius (though you could enforce one if you wanted - just beware of introducing discontinuous changes in the force field, which can look strange as the projectile shifts suddenly from one regime to another)
* accelerations are computed as a vector considering both x and y components, rather than treating the two separately
* integration and framerate independence is delegated to the physics system
> 1 votes

---
Tags: unity
---


# Question
Title: Setting up SFML with CLion on Windows 10
For a school project I am trying to set up SFML on my computer that runs Windows 10. The assignment is developing a small engine, based on SFML, in a few weeks. I am very new to C++, and I am not used to the working pipeline and the ways of C++ development yet.

At the moment I am trying to set things up so that I can work on the project from home, but I have a lot of trouble understanding and setting things up, since it's very different to what I'm use to.

My *CMakeLists.txt* file looks like the following:

```
cmake_minimum_required(VERSION 2.8.4)
project(CppEngine)
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake_modules")
if(WIN32)
    set(SFML_ROOT "$ENV{PROGRAMFILES(x86)}/SFML")
endif(WIN32)
set(CMAKE_BUILD_TYPE Release)
find_package(SFML 2.1 COMPONENTS system window graphics REQUIRED)
include_directories(${SFML_INCLUDE_DIR} ${PROJECT_SOURCE_DIR})
set(SOURCE_FILES main.cpp   )
set(HEADER_FILES            )
add_executable(CppEngine ${SOURCE_FILES} ${HEADER_FILES})
target_link_libraries(CppEngine ${SFML_LIBRARIES})

```

I get a very strange error message, as a result, whenever I try to compile and run. It is particularly strange, because I am running on *Windows*:

> error: #error This UNIX operating system is not supported by SFML library #error This UNIX operating system is not supported by SFML library

How can I fix this error?

# Answer
> 1 votes
CLion only supports Cygwin or MingW for Windows development. Cygwin is a compatibility layer for UNIX-like operating systems; MingW is a port of the UNIX development tools for creating native Windows applications. Microsoft's native development tools are unsupported by CLion according to their documentation.

Most desktop-like things such as games (that require OS-native features like graphics, audio, input, etc.) aren't going to work with Cygwin because it can't access native Windows APIs. You *can* eventually rig Cygwin up to run desktop apps on Windows, but the process is painful, the results are sub-par, and game frameworks like SFML will almost never bother to actually support such a configuration.

From a little Googling, others who've run into the SFML error you've posted were trying to use Cygwin. To SFML it looks like a UNIX system because that's what Cygwin pretends to be, hence why it thinks your Windows 10 OS is an "unknown UNIX operating system." The developers should properly detect Cygwin and at least provide a more accurate and detailed error ("SFML does not support the Cygwin environment; please use MingW if you wish to use UNIX development tools.") but that's their problem. :)

**Solution:**

You'll either need to

1. Configure CLion to use MingW

or

2. Switch to using the free and fully-featured Microsoft Visual Studio Community development tools instead of CLion so you can get first-class Windows development capabilities.

I recommend the second option very strongly. Unless your school's curriculum requires you to use CLion for some reason, in which case I recommend transferring to a better school. :)

---
Tags: c++, sfml
---


# Question
Title: How do I make an HTML5 canvas tiled map with tiles which have other than squared edges?
I'm creating an HTML canvas map and I'm trying to have the edges of the tiles not appear square, as in the tiles merge in to each other. I've scoured the internet for hours but can't seem to find anything. How would I go about doing this?

Dropbox link to project

I've included the used images so when the project is downloaded and run on the browser, the map should look like the following picture. This is not how I want it to look but how it currently looks.

I know it's probably not possible to get this exact effect using a tile based map, and it's not a perfect representation, but here's a general idea of what I want to accomplish. Notice how the corners are no longer squared but have a more rounded look and appear to be blending in with the next color tile. That's my goal.  Thanks in advance.

# Answer
> 3 votes
You need to create some transitional tiles like these:

 Image source: http://opengameart.org/content/lpc-more-water-transitions (licensed under CC-BY-SA 3.0)

As you can see there are tiles in this set which are half deep-water and half shallow-water. This allows you to design the transition from one texture to another in your image editor.

The same technique should be used whenever you transition from one ground type to another. Here is another example for a tileset which has transitions from sand to grass:

Source: http://opengameart.org/content/32x32-water-and-land-map-tilesets licensed under CC-0

You will notice that this tileset also includes transitions from textures to transparency. This allows you to place a half-transparent tile on an upper layer and full tile with a different texture on another layer behind it to blend them into each other automatically. How well that looks depends on the textures.

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Is Game Maker capable of creating my MMORPG?
I have an idea for a turn-based game MMO, and before starting the conception, I need to know if GameMaker is the right program to use. I already took some advice from this question, and I do not wish to open a discussion or seek an opinion. All I want to know is if it is possible to make my game in GameMaker.

### My Requirements

1. **The game is an MMORPG.** I have searched and found that *RizenEngine* allows a fully functioning, constantly updating MMO engine for Game Maker.

* The game needs to be hosted. I can start with one server, with a limited number of players.
    * The game needs to allow for security; not just of the game accounts, but I am already considering cheat prevention and frequent fixes whenever a new exploit is discovered by players.
2. **The game will feature an isometric map.** A simple 2.5D map is what I intend, if there are functionalities that eases the implementation of tiles for obstacles and back visions.
3. **The game will feature a variety of tactical movements and strategic spell .** I intend to make a turn-based battle system with a movement system and line of sight spell usage.

### Further Considerations

* The game will be something like Dofus or Yu Yu Hakusho: Tournament Tactics in the playing mode, without having to code from scratch or use old technologies like flash.
* I know it will be hard to make, and may take years, but that is irrelevant to the question.
* I am not asking for alternatives. I only need to know about GameMaker.

# Answer
> **The game is an MMORPG.**

If you're going to be serious about making an MMO with **Gamemaker**, you need to consider you'll be using plugins to handle the networking as **GM:Studio network handling functions** only really work for **WLAN LAN and Mobile**. You'd need to spend a lot of time learning about plugins to handle the networking, In fact you're probably going to need to learn **C++ or Javascript** to write the server code...... In addition to learning **GML**.

> **The game will feature an isometric map.**

A lot of tutorials proves that this can be made by **GameMaker** see this example

> **The game will feature a variety of tactical movements and strategic spell**

Tactical movement and spell use is completely possible with **GameMaker** and probably the easiest of the questions you have asked, although this is still a hard thing to get right in an isometric map.

This tutorial will be helpfull.

> **Global conclusion**

Yes GameMaker is capable of creating your MMORPG if you use the right plugins.
> 1 votes

---
Tags: mmo, game-maker
---


# Question
Title: Detect walking on floor - works partially
I have a set of Gameobject blocks that form a floor with Box Collider and a GameObject with a Box Collider in it.

My first hunch detecting hitting the floor was:

```
void OnCollisionEnter2D(Collision2D collision) {
    print ("Enter: " + collision.gameObject.tag);
    switch (collision.gameObject.tag) {
        case "Floor":
            isOnFloor = true;
            break;
    }
}

```

This works well. However, when I want to check whether he left the floor (falling):

```
void OnCollisionExit2D(Collision2D collision) {
    print ("Exit: " + collision.gameObject.tag);
    switch (collision.gameObject.tag) {
        case "Floor":
            isOnFloor = false;
            break;
    }
}

```

The GameObject Drops down as soon as I move a little, as I get the OnCollisionExit2D method...

How do I create a constant movement on a floor, and invoke "falling" only if I completely leave it?

Thanks!

# Answer
> 2 votes
Just like Vadim Tatarnikov said the reason why you fall is because your isOnFloor bool is set to false when you walk over to another block. to prevent all of this I would suggest going with the raycast way instead of box collisions. So to check if your GameObject is on the floor the best thing would be to cast a ray underneath this GameObject and see if there is a floor beneath it. This way you could also detect if your player is jumping by checking how long the Raycast is from your GameObject to the ground.

```
    float rayDistance = 100;
    RaycastHit hit;
    if (Physics.Raycast(transform.position, -transform.up, out hit, rayDistance))
    {
        //Hit is detected, you can now check with the RaycastHit how far away and what object you hit and apply logic there.
        Debug.Log("Raycast hit object " + hit.transform.name);
        Debug.Log("Distance between object and " + hit.transform.name + ": " + hit.distance);

        //You can even debug the line so you can see it in the scene
        Debug.DrawLine(transform.position, hit.point, Color.blue, 10);
    }

```

You should place this code in your update method for precise checking.

Here is the documentation of the Raycast https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

# Answer
> 0 votes
if you set the floor blocks to a new layer (ex. "Floor") you can detect it using `Physics2D.OverlapCircle()`

```
private bool isGrounded = false;
[SerializeField]
private LayerMask groundLayer;//set this to the Floor layer in the inspector

```

make a private bool isGrounded variable and in FixedUpdate() you can have it detecting the ground. Physics2D.OverlapCircle() can also be useful for detecting many layers such as ceilings, ropes, ice, ladders ect.

```
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundedRadius, groundLayer);

```

# Answer
> 0 votes
If you insist on using OnCollisionEnter and OnCollisionExit to detect if you are stepping on something, I'd suggest doing the following:

* Create a new variable of type `int`. Let's call it `StepOnCount`, init it to 0.
* Change the `OnCollisionEnter` to:

```
void OnCollisionEnter2D(Collision2D collision) {
    print ("Enter: " + collision.gameObject.tag);
    switch (collision.gameObject.tag) {
        case "Floor":
            StepOnCount++;
            isOnFloor = true;
            break;
    }
 }

```
* Change the `OnCollisionExit` to:

```
void OnCollisionExit2D(Collision2D collision) {
    print ("Exit: " + collision.gameObject.tag);
    switch (collision.gameObject.tag) {
        case "Floor":
        StepOnCount--;
        if(StepOnCount == 0)
            isOnFloor = false;
        break;
    }
}

```

This way you keep track on how many blocks you are stepping on: **You don't want to fall when you stop steping a block, you want to fall when you are stepping on no block.**

PD: If you are working on a 2D platformer, the other answers given here are a better approach. If you are working on a top-down or 3 fourths perspective game, I'd suggest using my solution.

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


# Question
Title: How can I check if a variable is relative to a number?
I would like to know how to check if a variable is relative to a number in Game Maker. An Example would be:

```
if variablex += 1
{
    DOTHIS
}

```

However this is not possible in Game Maker so I was wondering if there was some sort of equivalent that I could use.

# Answer
> 0 votes
This expression that you have in your `IF` is not really an expression. You just add 1 to `variablex` and it should be true always, meaning that `DOTHIS` is ran always.

```
variablex += 1

```

If structure in GameMaker

```
if (<expression>)
{
  <statement>
}

```

Say, you have variable `x` and you need to know if its value is `10`:

```
if (x == 10)
{
  DOTHIS
}

```

To compare `x` with other var increment:

```
if (x == y + 10)
{
  DOTHIS
}

```

I suggest that you read the manual once, to get some idea about programming in general. It's not easy stuff, but certainly nothing that you can't handle.

GameMaker manual - If statement

# Answer
> 0 votes
The Syntax of if condition is

```
if (<expression>)
   {
   <statement>
   ...
   <statement>
   }

```

But using **variablex += 1** means **variablex = variablex+ 1** which is always true. Condition should always be **variablex==1**

---
Tags: game-maker
---


# Question
Title: Adding mesh's\objects to procedural isosurface terrain
Thanks again for reading!

So following on from my last question, I have my fully working isosurface terrain and now its time to add my trees and grass and whatever to the world.

The old way I was doing it was to cast rays in a grid faceing down over the terrain, I would then read the normal from the ray hit and place things if the normal was \< as value.

I would do this at different grid resolutions for each plant\tree\grass time and offset there x, z and scale by some random value then adding the object to my 2d BV tree because I was only working with height map terrain so I only had one row of bounding volumes for the tree.

I can still use the above method but as you know it will only place objects on parts of the terrain that can see the sky.

Part of building my new terrain system involved making a real octree so I no that I will use that to store my objects but what is the best way to generate my object positons.

From what I have read around I should somehow use the voxels I build but I'm not really sure how I would go about it.

# Answer
> 1 votes
You should have the vertex positions for the terrain and some information about how they make up the triangles (like indices), and you also know the normals for each triangle.

With this data you can select a random triangle from the mesh, check if the normal is mainly pointing up (you should use dot product for this) and if it does, then that triangle is facing upwards, thus you can place something on it.

Now, choose a random point inside the triangle to place the object at.

(Depending on how small your triangles are, you may skip the next part as it makes no visible effect with small polygons.)

To make your objects seem like they are really attached to the ground you could get each vertices' height, and by using weighted average you can get the y position of that position on the triangle.

Take the distance of the random point to each vertex (here, d1, d2 abd d3) and do (y1, y2 and y3 are the height of the 3 vertex.

```
sum := d1 + d2 + d3
height := (y1 * d1 + y2 * d2 + y3 * d3) / sum

```

(If you want, you can add a random value to it)

Abd with this, you have the x, y and z coordinate if the object.

---
Tags: directx11, sharpdx, procedural
---


# Question
Title: Using PlayerPrefs to save audio volume throughout scenes in Unity
I have game that plays music. I have a mute toggle button that will mute my game music when you press on it, it will also un-mute it when you press it again. I'm having problems with saving the audio volume when a scene is loaded. (I tried using DontDestoryOnLoad but my mute script is attach to my main menu canvas so its saving the canvas as well, which I do not want. I find using playerprefs a lot easier). For example, when I click on my mute button, it mutes my game, I play the game, die, restart the game and the volume is being restarted as well. Even though I used playerprefs to try and solve the problem it didn't work, it still did the same thing. Anyway this is my script:

```
public bool mute;
public static Vector3 target;

void Start ()
{
    PlayerPrefs.GetFloat("mute");
}

void  Update()
{
    PlayerPrefs.GetFloat("mute");
}

private void Muted ()
{
    mute = !mute;
    if (mute) {
        gameObject.GetComponent<AudioSource> ().volume = 0;
        PlayerPrefs.SetFloat("mute", 0);
    }
    else
    {
        gameObject.GetComponent<AudioSource> ().volume = 1;
        PlayerPrefs.SetFloat("mute", 1);
    }
}

```

# Answer
> 1 votes
You are using the PlayerPrefs.GetFloat in update, which is a horrible idea.

I see that you have attached the script to a canvas. Instead, create a class called SoundManager. Have that attached to an empty gameobject in the intro scene that your game loads into. Make that a singleton and have a dontdestroyonload for this gameobject.

```
public class SoundManager : MonoBehaviour
{
    public static SoundManager instance;
    public bool mute{
        set{
            PlayerPrefs.SetFloat("muted", value ? 1 : 0);
        }
        get{
            return PlayerPrefs.GetFloat("muted", 0) == 0 ? false : true;
        }
    }
}

```

Then you can do a simple check on the toggle button click

```
SoundManager.instance.mute != SoundManager.instance.mute;

gameObject.GetComponent<AudioSource>().mute = SoundManager.instance.mute;

```

# Answer
> 0 votes
First of you'll have to create a class that encapsulates all game state varables that need to be saved/loaded , then you'll have to tag this class with \[Serializable\] , after that do the following :

```
[Serializable]
public class GameState
{
public int Volume;
public bool mute;
}

```

now create a class and add these two methods to it, and dont forgot to instantiate GameState and pass it to this class

```
public class GameSave : MonoBehaviour {
public GameState gm;
public void SaveData()
{
    if (!Directory.Exists("Saves"))
        Directory.CreateDirectory("Saves");

    BinaryFormatter formatter = new BinaryFormatter();
    FileStream saveFile = File.Create("Saves/save.binary");

    formatter.Serialize(saveFile, GameState);

    saveFile.Close();
}

public void LoadData()
{
    BinaryFormatter formatter = new BinaryFormatter();
    FileStream saveFile = File.Open("Saves/save.binary", FileMode.Open);

    gm = (GameState)formatter.Deserialize(saveFile);

    saveFile.Close();
}
}

```

# Answer
> 0 votes
You did not check and restore if the audio is mute or not.

```
void Start ()
{
    if(PlayerPrefs.GetFloat("mute") == 0)
    {
     gameObject.GetComponent<AudioSource> ().volume = 0;
    }
    else
    {
     gameObject.GetComponent<AudioSource> ().volume = 1;
    }
}

```

# Answer
> 0 votes
According to Unity's documentation:

> https://docs.unity3d.com/ScriptReference/PlayerPrefs.GetFloat.html
>
> > **public static float GetFloat(string key, float defaultValue = 0.0F);**
> >
> > Returns the value corresponding to key in the preference file if it exists. If it doesn't exist, it will return defaultValue.

What you need to do here is using GetFloat(key) to get the value that has been stored in the PlayerPrefs and assign it to AudioSource.volume.

Generally if you have values/references that are static (will not be modified), you can cache them in Start function for later use. And the update function is completely no need here.

As an example I rewrite you code as shown below:

```
public bool mute;
private AudioSource audioSource;

void Start ()
{
    // at the beginning we cache the needed references and read volume value from playerPrefs
    audioSource = GetComponent<AudioSource> ();
    audioSource.volume = PlayerPrefs.GetFloat("mute",1f); // we pass 1 as default value if nothing's found
}

private void Mute (bool value)
{
    mute = value;
    var volume = mute ? 0f: 1f;
    if(audioSource )
         audioSource.volume = volume ;
    PlayerPrefs.SetFloat("mute", volume );
}

```

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


# Question
Title: How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d
I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script :

```
using UnityEngine;
using System.Collections;

public class hu : MonoBehaviour {
GameObject[] pauseObjects;
public bool isPaused;
 void Start () {

 pauseObjects = GameObject.FindGameObjectsWithTag("Player");

 }

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

  {
   if(Time.timeScale == 1)
   {
    Time.timeScale = 7f;

   } else if (Time.timeScale == 8f){

    Time.timeScale = 1;

   }
 }
}
}
```

# Answer
> 2 votes
In Unity 5.4 you can use the built-in WaitForSecondsRealtime in your coroutine to safely modify timescale and avoid problem with WaitForSeconds when having timeScale == 0 as @DMGregory mentioned

https://docs.unity3d.com/ScriptReference/WaitForSecondsRealtime.html

So it would be something like :

```
using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour
{

    public void PauseAndAutoUnpause(float pauseTime)
    {
        StartCoroutine(PauseAndAutoUnpauseCoroutine(pauseTime));
    }

    IEnumerator PauseAndAutoUnpauseCoroutine(float pauseTime)
    {
        Time.timeScale = 0f;  // set timeScale to 0 will make your game paused
        yield return new WaitForSecondsRealtime(pauseTime);
        Time.timeScale = 1f; // we unpause the game by setting timeScale to its normal value, 1
    }

}

```

# Answer
> -1 votes
You should use Coroutines.

```
void Pause(){
  StartCoroutine(waitToUnpause);
}

IENumerator waitToUnpause(){
  //do the thing to pause game
  Time.timeScale = 7f;//or some other method
  yield return new WaitForSeconds(7);///or any duration you want
  Time.timeScale = 1f;//or some other method
}

```

---
Tags: unity, unityscript, gameobject, pausing
---


# Question
Title: Fragment shader operations before vector transformations
I feel like I'm misunderstanding how to work with vector/fragment shaders. My vector shader is as follows:

```
uniform mat4 uVMatrix;    // view (camera transformations)
uniform mat4 uMMatrix;    // model (object transformations)
uniform mat4 uPMatrix;    // projection
attribute vec4 aVertexPosition;     // passed in
attribute vec4 aVertexColor;
varying vec4 vColor;

void main() {
    gl_Position = uPMatrix * uVMatrix * uMMatrix * aVertexPosition;
    vColor = aVertexColor;    // pass the vertex's color to the fragment shader
}

```

Pretty simple. Right now I just have a simple square that I'm transforming in 3D space and drawing. I want to make a see through circle in the middle of the suqare as follows:

This square has 4 vertices that I transform in the vector shader. Here's my fragment shader:

```
precision mediump float;    // how precise to be with floats
varying vec4 vColor;        // interpolated from the vertices

void main() {
    gl_FragColor = vColor;
}

```

Now, I've seen I have access to gl\_FragCoord, but that coordinate is after all the vector transformations, right? How can I manipulate the pixels in the square, before all the projection transformations, etc.? I don't think I can do it in the vector shader, as there's only 4 vectors...

# Answer
> 1 votes
A simple way to achieve this would be to assign UV to your quad mesh, and then you can utilize that UV in your fragment shader to draw the circle by doing something like this (pseudocode):

```
color = uv.magnitude > 0.5f ? invisible : visible

```

This will work because the UV's are interpolated over the polygon.

---
Tags: shaders, opengl-es, opengl-es2, fragment-shader
---