texts: How to detect if instantiated prefab can be placed at current location or not

texts:
I'm using Unity 5.5.0f3 with C#.

My prefab(wooden fence) is instantiated at my mouse location when I click a UI button and follows my mouse until I click somewhere in the scene to place it. The fence has a box collider on it.

Currently, the fence is able to be placed intersecting and even inside of anything else on the scene right now, and I want to eliminate this issue.

I would like my fence (and any other future prefabs) to check if it is intersecting an object's collider when it is following my mouse and turn red if it is, or else be green if it is not to indicate if it can or cannot be placed there and either allow or deny placement accordingly.

I have read that there is no way to do this using transform.position since this is essentially using teleportation on my fence. I tried to use GetComponent<Rigidbody>().MovePosition(hit.point + positionOffset); but I get all kinds of weird behavior when I do this.

The following are the three scripts I am using to make this happen:

Raycast Builder:

public class RaycastBuilder : MonoBehaviour {

    public GameObject defense;
    public Vector3 positionOffset;

    public bool IsPurchased = false;

    public float speed = 2f;

    Vector3 mousePosition;

    BuildManager buildManager;

    void Start ()
    {
        buildManager = BuildManager.instance;
    }

    void Update ()
    {
        GameObject defenseToBuild = buildManager.GetDefenseToBuild();
        if(defenseToBuild == null)
        {
            return;
        }

            //To get the current mouse position
            mousePosition = Input.mousePosition;

            Ray ray = Camera.main.ScreenPointToRay(mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1 << 8))
            {
            defenseToBuild.transform.position = hit.point + positionOffset;

            if (Input.GetKey(KeyCode.E))
                {
                    defenseToBuild.transform.Rotate(Vector3.up * speed * Time.deltaTime);
                }
            if (Input.GetKey(KeyCode.Q))
                {
                    defenseToBuild.transform.Rotate(-Vector3.up * speed * Time.deltaTime);
                }
        }

        if (Input.GetMouseButton(0)&& IsPurchased == true)
        {
            buildManager.SetDefenseToBuild(null);
            IsPurchased = false;
        }

        if(Input.GetKeyDown(KeyCode.Escape))
        {
            buildManager.SetDefenseToBuild(null);
            Destroy(defenseToBuild);
            IsPurchased = false;
        }
    }
}

Shop:

public class Shop : MonoBehaviour {

    BuildManager buildManager;

    void Start ()
    {
        buildManager = BuildManager.instance;
    }

    public void PurchaseWoodenFence ()
    {
        Camera.main.GetComponent<RaycastBuilder>().IsPurchased = true;
        Debug.Log("Wooden Fence Started");
        buildManager.SetDefenseToBuild((GameObject)Instantiate(buildManager.woodenFencePrefab, Vector3.up, Quaternion.identity));
    }

}

Build Manager:

public class BuildManager : MonoBehaviour {

    public static BuildManager instance;

    void Awake ()
    {
        if (instance != null)
        {
            Debug.Log("More than one BuildManager in Scene!");
            return;
        }
        instance = this;
    }

    public GameObject woodenFencePrefab;

    private GameObject defenseToBuild;

    public GameObject GetDefenseToBuild ()
    {
        return defenseToBuild;
    }

    public void SetDefenseToBuild (GameObject defense)
    {
        defenseToBuild = defense;
    }

}


texts: Use Slick2D for standard application instead of game

texts:
I was wondering how well Slick2D would work when used for a custom rendered GUI in a standard application?  A standard application not being a game.  More like a text editor or 2D level editor that doesn't strictly need to render at 30/60fps.

More specifically, can Slick2D be configured to only render when a change has occurred in the user interface?

Background: I want to develop a level editor for a 2D puzzle game called Enigma that takes advantage of hardware rendering and cross platformness offered by Slick2D.  I have decided that implementing the whole interface with Slick's rendering will give me the greatest flexibility when it comes to user interaction.  However, rendering at a constant fps would be a bit wasteful, which is why I ask the question above about rendering only when needed.


texts: How should I proceed next with my programming skills?

texts:
I am currently studying at University of technology in Brno (Czech Republic). This semester is almost over and I might say I have some knowledge of C. Since I went to this school just for the purpose to become a game programmer I would like to start programming a game asap.

My school project are almost done so I have been thinking about writing something already (story driven game running in terminal ^^). But this won't satisfy me.

My question is how should I proceed next? I did my homework and went trough similar questions but I didn't get the answer. I hope this question won't be closed. People are usually mentioning C++, C#, OpenGL and others and I simply don't know which one to choose.

I am currently interested only in 2D games and that won't change for some time. I don't want my game to run on a mobile device yet and I want to make games for PC and Mac, not for consoles obviously. Which language does fit my needs the best?


texts: Reducing overdraw cost: does triangle ordering matter?

texts:
I'm working on a project with procedural geometry, and will potentially have lots of opaque faces overlapping within the same model. Imagine an onion's layers. My understanding is it is better to draw the outermost layers first so inner layers' pixels can be discarded quickly by z-buffer test. If so, does that mean I should put the outermost triangles first in the index buffer for the best performance?

For reference, I'm using Unity.


texts: How to program a cutting tool for 3D model in game

texts:
I'm looking for a resource to figure out how to program a function to cut a 3d model in game.

Example: Enemy/NPC is sliced into 2 pieces with a sword. His body is not hollow, you can see bloody texture where normally a 'polygon hole' would be.

The first step is to actually 'cut/slice' the model, then add in polygons to fill the hole in the model. I know this can be done in 3D modelling software, but I'm not sure how to go about doing this in a game, code-wise. I do not wish to use 'pre cut-up" models, the code will determine where the cut is.

Any pointers in the right direction would be greatly appreciated.


texts: Procedurally generated satellite view textures for large landmass rendering

texts:
I'm rendering a big land mass to be viewed from high altitude (40+ km), so I need satellite view style textures to be generated on the fly. The per vertex attributes I've got are:

Biome (forest, snow, desert, mountain, etc)
Elevation
Moisture
Temperature

Question is, is this even possible by solely shader code without any textures to sample from? It's downright impossible to find a decent looking texture pack for satellite view style textures. So far all techniques I've found were based on generating textures on existing terrain data, what I need is a procedural way to generate those on the fly per arbitrary terrain.

This is more or less the looks I'm aiming to achieve with already generated mesh and more biomes(tundra, desert, bare, shrubland, etc) and perhaps more "zoomed in":


texts:
Should I

Cast new bullets from my Weapon class, which would test a flag when its updated that tells if mouse left is down, which is set by Input class
Cast new bullets from my Input class, which would call Weapon Cast()

And why?


texts: Gravity independent of game updates per second

texts:
Edit

Just for clarification, my sprite's 'movement' isn't the problem. If I set my Time variable to 4 seconds, then it will cross the screen in exactly 4 seconds regardless of logic updates rate per second, rendering rate per second or screen resolution.  So I am pretty sure I'm scaling the sprite's movement correctly.  What I'm pretty sure I'm not doing correctly, is scaling acceleration.

Original Question

I'm trying to implement gravity in my 2d platformer and am having a few problems understanding how to keep it consistent when I change my updates per second.

Here's what I have.

My Gameloop overview

Currently, my gameloop renders at the maximum rate allowed by device and the updates are 'clamped' to an upper limit (At the moment, 60 per second). I am working on the assumption that most of the time, my game will have no problem hitting this, even if the actual rendering dips. Thus I am doing all of my calculations based Delta Time derived from this fixed 'ticksPerSecond' value.

I don't know for sure that this will remain at 60, I may decide at some point during the development to lower this upper limit.

My Gravity - variable declaration and initial values

At the moment, I have:

float spriteYTime=7f;                //This is the (initial) amount in seconds that this sprite will take to move from the top of the screen to the bottom.
float fallAccel=.5;                  //This is the value that will subtracted from he sprite's fall speed (To make it fall ever faster)
float terminalVelocity=1.5f;         //Cap speed at this rate (1.5 seconds)

my sprite's position is worked out on dt as follows:

//Delta time
float ticksPerSecond = 60;
float dt = 1f/ticksPerSecond;
//Velocity
spriteYVel = 1/spriteYTime;
//Update position
spriteYReal = spriteYReal + (spriteYVel * dt);
//Convert to screen coordinates (will be drawn at this Y coordinate)
spriteyScreen=(int) (furmanYReal*height);

My Gravity - code

    //If my sprite's state is 'f' (meaning falling) then apply gravity
    if(sprite.getState('f')==true){
    //Calculate new position
    spriteYReal = spriteYReal + (spriteYVel * dt);
    //Convert to screen coordinates
    sprite.yScreen=(int) (spriteYReal*r.height);
    //Reduce time by fallAccel amount & update velocity value based on new time value (So sprite falls slightly faster this frame compared to the last
    spriteYTime-=fallAccel;
    spriteYVel = 1/spriteYTime;
    //Check that speed isn't faster than terminal velocity
         if (spriteYTime<spriteVelocity)
            spriteYTime=spriteVelocity;
    }

The problem

Now, this does work, but if I change my ticksPerSecond value, it goes wrong (it falls at different rates).

I know that 'Earth Normal' gravity is approximately 9.8 meters per second per second, but this is measured 'per second' whereas I (think) I need to work with 'per frame'. This is where I'm getting confused.

So, take this example:

If set my initial Time value to 4 seconds, then if it remained constant at this speed, it would take 4 seconds to reach the bottom, if I changed my ticksPerSecond, because the time value is worked out using delta, it would still take 4 seconds but if I apply 'fallAccel" to the Time value (i.e. subract it), it goes wrong when I change the ticksPerSecond value - why?

How can I get this to fall at the same rate regardless of the value of 'ticksPerSecond' - any help in understanding this would be appreciated.


texts: How to properly handle errors in a D3D11 framework?

texts:
I'm writing a D3D11 framework and I'm trying to clean it up a little, and I'm unsure how to handle errors and return codes in my classes/code.

What is the "best" and cleanest way to implement error handling ?

Should I just use the HRESULT and other D3D types as return values for errors and such, or should I create my own types, or should I go with native c/c++ types ?


texts: How to share Unity High Scores on social media (Facebook , Google+ and Twitter)?

texts:
This may be a common question but as a n00b I have some confusion on achieving this .

I am on a small game project and I want the user to share his / her scores on social media after completing the game .

When they post , it should be something like "Hurrayyyy ! I Scored 12345 on -My Game App Name- , Can you beat my score ? Try it ." where '-My Game App Name-' and 'Try it' should be a link directing to Google Play / Windows Store etc .

My Idea is like this :-

Here Share This on Facebook , Share This on Google+ and Share This on Twitter are 3 UI Images with Button component attached to them .

So when the player clicks on those buttons , they should post on social media .

So how to achieve this ? I got something here , but I don't know how to use that . I will prefer not to use Facebook Unity Plugin . So can I achieve this ?
I need code in c# , not in JavaScript :)

I hope you will help me to figure this out .

Regards , NB :)


texts: change the position of f3d objects randomly in action script

texts:
I have a f3d object and have different boxes to place the parts of the f3d objects.When i click on the button change the position of the boxes randomly. How it possible?This is the code for random array.

private function init(e:Event = null):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        // entry point

        var startArray:Array = generateNumberArray(10);
        var randomArray:Array = randomArray(startArray);
        trace("startArray = " + startArray);
        trace("randomArray = " + randomArray);

    }
    /**
     * generate Array of numbers by length
     * @param   length
     * @return Array of numbers
     */
    public  function generateNumberArray(length:int):Array
    {
        var numberArray:Array = [];
        for (var i:int = 0; i < length; i++)
        {
            numberArray[i] = i+1;
            //trace("ersexrfegtdrgtdrygtfr"+numberArray[i]);
        }

        return numberArray;
    }

    /**
     * generate randomly mixed array by input array
     * @param   inputArray - simple not mixed array
     * @return Array - mixed array
     */
    public function randomArray(inputArray:Array):Array
    {
        var randomArray:Array = [];
        var tempArray:Array = [];
        for (var i:int = 0; i < inputArray.length; i++)
        {
            tempArray.push(inputArray[i]);
        }
        while (tempArray.length)
        {
            var randomNumber:int = Math.round(Math.random() * (tempArray.length - 1));// get random number of left array
            randomArray.push( tempArray[randomNumber] );
            tempArray.splice(randomNumber, 1);
            trace("randommmmmmmmmmmmmmmmmmmmmmmm"+randomArray);

                 // remove randomed element from temporary aarray
        }
        tempArray = null;
        delete [tempArray];
        return randomArray;

    }
    public function loadCompleteEvent(e:Event):void
    {
      if (stage) init();
        else
            addEventListener(Event.ADDED_TO_STAGE, init);

         // my boxes (want to change the position randomly of these boxes)
        Box2.setPosition(57.49752426147461, -2.987499237060547, 10);
        Box3.setPosition(57.49752426147461, -26.987499237060547, 10);
        Box4.setPosition(-48.50247573852539, -2.987499237060547, 10);

}


texts: "Cut the Rope" is so smooth and real life like, while some apps are very "bitmap" like.  How does "Cut the Rope" do such realistic animation?


texts: Is IDirectInput8::FindDevice totally broken on Windows 7?

texts:
I'm developing on Windows 7, and using DirectInput8 for my input needs.
I'm tracking gamepad additions and removals (that is, GUID_DEVINTERFACE_HID devices) using the DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE messages, which works fine.

However, what I've come to find out is that no matter what I do, passing the received values from DBT_DEVICEARRIVAL to IDirectInput8's FindDevice method, it will always fail to identify the device, returning DIERR_DEVICENOTREG.

DirectInput still clearly knows about the device, because I can enumerate and create it just fine.
I've tried with three different gamepads, and the error persists, so it's not about that either.
I also tried passing some alternative interface GUIDs for the RegisterDeviceNotification call, didn't help.

So, has anyone else faced the same problem, and have you found a usable workaround?
I'm afraid I'll soon have to stoop down to re-enumerating all devices when something is added or removed, but I'll first give this question one last shot here.

EDIT: For the record, I've also tried pretty much every single HID API & SetupAPI function for alternative ways of figuring out the needed GUIDs, with zero success. So if you're facing the same problem as me, don't bother  with that route. I'm pretty sure those GUIDs are made up by DirectInput itself somehow. Short of reverse engineering dinput8.dll, I'm truly out of ideas now.


texts:
I'm still quite a beginner in the industry. I'm working on a game with some friends and I would like to add a cinematic between 2 levels like in the attached picture.

My question is how can I render the black bars in DirectX 9 or 11? Moreover, do I need to change the aspect ratio when I'm playing the cinematic?


texts: Where should I store textures for a game?

texts: I am currently creating a game in SFML using C++ and I'm wondering: what is good practise for a location for textures? Should I store it with my project? Or my executable? Or even in something like the Documents folder? What would be the most efficient when the game would theoretically be released, as it will not simply include the project but rather a compiled and build version of it?


texts:
I am a web developer new to game development, and with limited math knowledge. I am writing a character movement controller in Unity. The game has an isometric Diablo-like camera. The character moves on mouse click within a limited area.

The character moves like this now:

I want it to move like this:

I don't need you to write the code for me: I just want to understand what the math for this looks like. A Unity- and C#-specific explanation would be great, but not necessary.


texts: Moving a camera without rolling (tumble not arcball rotation)

texts:
I'm trying to move my camera around using mouse+keyboard. I'm looking for specific camera behaviour however, and I cant figure out how to get it right. What I've found, is that to get a maya/tumble style camera, I need to multiply my xrotation in world space then my yrotation. Reversing the order it looks like this:

view = cam_move * //wasd in cam_space, this works correctly
       yrot * //before = world to camera space
       view*
       xrot; //after = model to world space

This means my xrot(world) doesn't interfere with my yrot(eye), which avoids unwanted roll induced by regular cam-space x-rotation.

My problem however, is that I want the xrotation to happen around a point (as if done in eye space) but without creating unwanted roll. I do not know how to get that result.

According to my sources It should be as easy as translating inversely before xrotating, then translating back after, but its just not working. Perhaps someone knows how I can get my cam to spin (yaw) around a point, without causing the unwanted roll?

SOLUTION:

Keeping track of pitch/yaw (mouse_move.xy) seperately, as well as the camera location, and making sure to multiply the yaw before the pitch. Pitching will create unwanted roll, but yawing wont create unwanted pitch, so its a matter of which you do first here.

To move the camera in eye space, I do this:

//make a mat3 rotation matrix and multiply it with current movement
if (keys['A'] - keys['D'] || keys['W'] - keys['S']){
    camlocation += //rotated then moved
        (glm::normalize(vec3(keys['A'] - keys['D'], 0, keys['W'] - keys['S']))*move_speed)*
        mat3(glm::rotate(mat4(1.0f), pitch, vec3(1, 0, 0)))*
        mat3(glm::rotate(mat4(1.0f), yaw, vec3(0, 1, 0)));
} //which will be a value to add in world space

Then under camera update, or where I build the view matrix, I do this:

view =
    glm::rotate(mat4(1.0f), pitch, vec3(1, 0, 0))* //pitch radian float
    glm::rotate(mat4(1.0f), yaw, vec3(0, 1, 0))* //yaw also in radian
    glm::translate(mat4(1.0f), camlocation);

Just remember that in OpenGL/GLM the matrix transformations are reverse order, due to how OpenGL does column/row matrix computations. (Compared to directx it saves a transpose operation in the shader (apparently))

Making sure to yaw before pitching, and both after translating (reversed on paper) avoids the unwanted roll, wich yields the desired tumble/maya effect!


texts: Is there a expected set of button mappings games commonly use?

texts:
I am making a game that will support a XBox 360 controller but I would like to try and keep the default button mappings to be what is expected from a user's past history from playing other games. Is there a set of guidelines from Microsoft on what should map to what (do you use A for fire or left trigger?), or has the gaming community picked up a common set of controls that is just not written anywhere, everyone just "knows" it (like WASD for movement).

The hardest thing for me is I have walking movement, vehicle movement, and airplane movement. I plan on allowing custom configuration of each, but I don't know what to set as the defaults.


texts: Implementing ClearPath (crowd pathfinding)

texts:
This is the academic article:

http://gamma.cs.unc.edu/CA/ClearPath.pdf

Here is the confusing part (marked in red):

The first part is the path in which the object will move.

The first part of the formula in the red frame defines the sets of all possible velocities for agent A that will result in collision with obstacle B in the future (a cone).

I don't understand why they XOR the subtraction of A from that formula? I don't understand what it means to do exclusive or a substructed set?I want to understand it better.


texts: How to use objects with different attribute values in Swift?

texts:
I think this is a really basic question and to make it easier to understand what I do not understand, I use the following scenario.

Scenario: I have two or more ships in my game. They should have different attributes like name, hitpoints and score. I want shoot at them and get score points for it.

My approach: I extended SKSpriteNode to get my own ship class. And when I fire a bullet collision detection will tell me when it hits.

import SpriteKit
class ship: SKSpriteNode {
        var hitpoints: Int = nil?
        var score: Int = nil?

    func createPhysicsBody(){
        self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
        self.physicsBody?.dynamic = true
            ...
    }
}

func didBeginContact(contact: SKPhysicsContact){
    switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
        case shipCategory + bulletCategory:
            contactShipBullet(contact.bodyA, bodyB: contact.bodyB)
            break;
        default:
            break;
    }
}

Problem:  Swifts collision detection returns physicsBody objects and their parent is the game scene. So I do not know the SKSpriteNode of this physicsBody nor ship's hitpoints (to decrease it by 1) or score.

Thought: At the end I am not sure if my approach is a good one. What should be the best way to give objects on screen attributes and how can I get/change those attributes after a collision is detected by the physics engine?


texts: Information about rendering, batches, the graphical card, performance etc. + XNA?

texts:
I know the title is a bit vague but it's hard to describe what I'm really looking for, but here goes.

When it comes to CPU rendering, performance is mostly easy to estimate and straightforward, but when it comes to the GPU due to my lack of technical background information, I'm clueless. I'm using XNA so it'd be nice if theory could be related to that.

So what I actually wanna know is, what happens when and where (CPU/GPU) when you do specific draw actions? What is a batch? What influence do effects, projections etc have? Is data persisted on the graphics card or is it transferred over every step? When there's talk about bandwidth, are you talking about a graphics card internal bandwidth, or the pipeline from CPU to GPU?
Note: I'm not actually looking for information on how the drawing process happens, that's the GPU's business, I'm interested on all the overhead that precedes that.

I'd like to understand what's going on when I do action X, to adapt my architectures and practices to that.

Any articles (possibly with code examples), information, links, tutorials that give more insight in how to write better games are very much appreciated. Thanks :)


texts: Unity: Editing a DontDestroyOnLoad object in another scene

texts:
I figured out how to make certain objects like my Camera and Canvas persist across scenes, but I can't figure out how to access them in the editor from scenes in which they're not instantiated.

I can make these objects prefabs and make my changes to the prefab rather than the instance, but then I can't make references in the prefab to objects in the hierarchy; I would have to use an instance of a prefab to do that.

How can I edit subsequent scenes in the same way that I edited the first scene, where all the DontDestroyOnLoad objects are instantiated for the first time and I can access them through the hierarchy?


texts: How can I fade something to clear instead of white?

texts:
I've got an XNA game which essentially has "floating combat text": short-lived messages that display for a fraction of a second and then disappear.

I've recently added a gradual "fade-away" effect, like so:

 public void Update()
        {
            color.A -= 10;
            position.X += 3;
            if (color.A <= 10) isDead = true;
        }

Where color is the Color int the message displays as. This works as expected, however, it fades the messages to white, which is very noticeable on my indigo background.

Is there some way to fade it to transparent, rather than white? Lerp-ing towards the background color isn't an option, as there's a possibility there will be something between the text and the background, which would simply be the inverse of the current problem.


texts: How do you increase the spacing on text within LibGDX labels

texts:
So I'm following along with some tutorials for creating an application with LibGDX, and when I go to print parts of the UI to the screen, the text is all bunched up. How do I increase the spacing, or is it due to something else I've done?

....
    game = gam;
    stage = new Stage(new StretchViewport(800, 400));
    Gdx.input.setInputProcessor(stage);
    uiSkin = new Skin(Gdx.files.internal("uiskin.json"), new TextureAtlas(Gdx.files.internal("uiskin.atlas")));
    Label nameLabel = new Label("Name:", uiSkin);
    TextField nameText = new TextField("", uiSkin);
    Label addressLabel = new Label("Address:", uiSkin);
    TextField addressText = new TextField("", uiSkin);

    table = new Table();
    table.add(nameLabel).expandX();
    table.add(nameText).width(200);
    table.row();
    table.add(addressLabel);
    table.add(addressText).width(200);
    table.setFillParent(true);
    stage.addActor(table);
    table.setDebug(true);


texts: What is the impact of many AI enemies on state replication networking?

texts:
Imagine an online coop style FPS or TDS game where say 2-6 real players fought large amounts (20-60 concurrent) of AI enemies. Could this style of game be reasonably networked over the internet using a Quake or Tribes style partial state replication model? Almost every coop game I know of uses a lockstep style networking in these cases (even games like Halo which use state replication for normal multiplayer, but lockstep for coop/firefight). My concern is that the network download (for clients) and upload (for server) overhead of each AI would end up being about the same as if a real player was in the game. Is this a real concern? Or is the limiting factor on the number of players more about how much data the players upload?

TLDR; Can large numbers of AIs be reasonably networked to a few players with a partial state replication model or is lockstep the only real solution.

Any help here would be great!


texts: As an Independent Developer should I host my own official game servers

texts:
My small team is approaching initial closed alpha for testing, however that has brought up the question of whether it is a good idea to host our official game instances from my home office or not. I've run a few dedicated servers before on my home PC (have 3 active as a service at the moment actually) so I'm not unfamiliar with the process. However I'm looking into building a server PC specifically to fulfill that singular purpose. I have google fiber 1000mbps so I don't think I'll have bandwidth issues. But I wonder if any of you have advice and insight into what I should expect, dangers to avoid, etc.

Here's what I anticipate, am I missing anything?:

Masking home IP via dynamic DNS service - (pointing to a website to login rather than an IP)
Running multiple VMs on a single server to easily manage server resources
Initially testing with a few selected users
Eventually open up to more users once proven stable


texts: How to calculate the closing speed of two objects

texts:
I have the 2D positions and 2D velocity vectors of two objects. How do I calculate the closing velocity ? I want to get the closing speed.

Think of one jet tracks another jet with radar and you want to yield the closing speed, which is actually the distance-change / unit. (In this example Δmiles/h)


texts: I dont understand how exactly stencil buffer works in openGL. One aspect that confuses me is why do we use a bit operator there in glStencilFunc. Some text say that is is used to achieve multiple stencil planes but I am not sure how that can be done. Can anybody please explain the whole procedure of stencil buffer calculation during the rendering cycle. Thank you.


texts: How to add prefabs to the terrain and still retain scripts, colliders, etc.?

texts:
I have been working on an old DOS-styled game, and I began work on the trees for my terrain. Here is a group of them:

They, right now, are simply objects in the scene. This works, but is very cumbersome when mass placing them. I want to have them part of the terrain. I tried simply adding them as a detail mesh, but they didn't retain scripts nor colliders. Is there a way to accomplish this?


texts: Scale smaller resolution to full resolution libGDX

texts: Short question about the scaling in libGDX. At the moment i have a application with the resolution 480x320. I define this in the main method of the desktop launcher. My whole application is now calculating with this resolution. For example is the player 50x50 pixels. How can i now scale my application to, for example, 1920x1080 on android so my player is now not only 50x50? I use a orthographic camera and give the width and height of 480x320 in the constructor.


texts: How to display a hierarchical skill tree in php

texts:
If I have skill data set up in a tree format (where earlier skills are prerequisites for later ones), how would I display it as a tree, using php?  The parent would be on top and have 3 children. Each of these children can then have one more child so its parent would be directly above it.

I'm having trouble figuring out how to add the root element in the middle of the top div, and the child of the children below each child of the root.  I'm not looking for code, but an explanation of how to do it. My data in array form is this:

Data:

Array
(
    [1] => Array
        (
            [id] => 1
            [title] => Jutsu
            [description] => Skill that makes you awesomer at using ninjutsu
            [tiers] => 1
            [prereq] =>
            [image] => images/skills/jutsu.png
            [children] => Array
                (
                    [2] => Array
                        (
                            [id] => 2
                            [title] => fireball
                            [description] => Increase your damage with fire jutsu and weapons
                            [tiers] => 5
                            [prereq] => 1
                            [image] => images/skills/fireball.png
                            [children] => Array
                                (
                                    [5] => Array
                                        (
                                            [id] => 5
                                            [title] => pin point
                                            [description] => Increases jutsu accuracy
                                            [tiers] => 5
                                            [prereq] => 2
                                            [image] => images/skills/pinpoint.png
                                        )

                                )

                        )

                    [3] => Array
                        (
                            [id] => 3
                            [title] => synergy
                            [description] => Reduce the amount of chakra needed to use ninjutsu
                            [tiers] => 1
                            [prereq] => 1
                            [image] => images/skills/synergy.png
                        )

                    [4] => Array
                        (
                            [id] => 4
                            [title] => ebb & flow
                            [description] => Increase the damage of water jutsu, water weapons, and reduce the damage of jutsu and weapons that use water element
                            [tiers] => 5
                            [prereq] => 1
                            [image] => images/skills/ebbandflow.png
                            [children] => Array
                                (
                                    [6] => Array
                                        (
                                            [id] => 6
                                            [title] => IQ
                                            [description] => Decrease the time it takes to learn a jutsu
                                            [tiers] => 5
                                            [prereq] => 4
                                            [image] => images/skills/iq.png
                                        )

                                )

                        )

                )

        )

)

An example would be this demo image minus the hover stuff.


texts: Accessing RigidBody2d from OnTriggerEnter2D(Collider)

texts:
I have the following script on my water object which, when the Players ship triggers it, the ships gravity is inverted to give the sense of buoyancy. I have added a 'print' statement to prove that the collision is working and that the Name condition check works, which it does. However it throws an error when trying to access the plays ship Rigidbody2D property to then access the GravityScale with the message:

There is no 'Rigidbody2D' attached to the "Player" game object, but a script is trying to access it.
You probably need to add a Rigidbody2D to the game object "Player"...

void OnTriggerEnter2D(Collider2D coll)
{
    if (coll.gameObject.name == "Player")
    {
        print("Player Hit Water");
        Rigidbody2D tmp = coll.gameObject.GetComponent<Rigidbody2D>();
        tmp.gravityScale *= -1;
    }
}

Update: It turns out this code is fine it was the structure of my gameobjects  that was the problem as the Rigidbody2D was in the child object, not the parent. See comments below for details.


texts: How to fix overly blurred texture / image in unity?

texts:
so, I'm not sure what caused this, let image below do the explanation :

How to fix the overly blurred texture in unity? It's so frustrating, since I can't get it right, because when I tried it in LibGDX, the image looks good (Well, it's not exactly a same image, but similar).

They both screenshot from android device (Samsung Galaxy Note 3 Neo)

Thanks

P.S. It's a pixel art

Edit, here's the screenshot of my relevant inspector window

And here's the alpha ingame screenshot


texts: How do I move a 3D particle using the Mercury particle engine?

texts:
I'm currently creating a 3D game with XNA, and I am in need of some particles.That's why I searched for a particle engine. I found Mercury, watched the tutorials and integrated it in the game.

But now I have a problem, I trying to have particle in 3D but I don't how to do this with Mercury. How can I do this (is it even possible)?


texts: Non-destructive way to edit alpha channel in Photoshop/Gimp image

texts:
Looking to make textures for Unity3d, and I'm stuck at what seems to be a simple stage. My goal is to create an RGBA image, with color information for every pixel, and a separate alpha channel. These two components get fed into Unity as base color and reflection strength, respectively. (Using "Reflective/Bumped Diffuse" material.)

If I use masking tools in Photoshop, I can erase parts of the output image (transparency). However, I would like to keep the original RBG color information when output, and not just have "blank" areas. Also, it would be nice if I could do it non-destructively, ie. the final alpha channel is dependent on a standard layer, or built from a path object, etc.

I have the same problem with The Gimp.

Any help on this would be greatly appreciated.

(If Photoshop/Gimp are not the tools for the job, can someone please recommend a better one?)


texts: Rotating and Translating a Node in Horde3D with Matrices and Quaternions

texts:
I have been trying to learn how to use the Horde3D rendering engine for the past couple of days,
and so far I have managed to learn a decent amount and integrate Bullet Physics with it as well.

My problem is in my maths for rotating and translating a node in Horde3D to keep it in sync with Bullet Physics.

I have a terrain and a sphere, both of which are in the Bullet Physics dynamics world.
The sphere drops from the sky and hits the terrain and everything works fine and collides/moves around as it is supposed to.

The problem is that I can successfully translate the 3D model in Horde3D to stay in sync with the position of the sphere shape in Bullet Physics,
but as soon as I try to introduce rotation things start to go wrong.

It's a bit difficult to describe so I have uploaded a video of the problem to YouTube (below).
Basically, the green wireframe is the Bullet Physics sphere shape, and the brown sphere is the sphere at the Horde3D node.

Everything is fine while the sphere is falling, because there is no rotation, but as soon as it hits the terrain and rotation
is supposed to take place the Horde3D node moves in a completely different direction to the Bullet Physics wireframe.

You can see what I mean by watching the video here: http://www.youtube.com/watch?v=Yi_DJIWpxOo&feature=youtu.be

I assume this is probably a quaternion/multiplication/matrix/order of multiplication error of some kind, but I can't figure it out myself.

Horde3D provides two ways that I know of to set a node's position.

They are:

h3dSetNodeTransform (http://www.horde3d.org/docs/html/_api.html#h3dSetNodeTransform)
h3dSetNodeTransMat (http://www.horde3d.org/docs/html/_api.html#h3dSetNodeTransMat)

I could use h3dSetNodeTransform and set all of the Euler angles, but Bullet Physics provides a quaternion,
so I would rather try and use translation and rotation matrices instead of converting the quaternion to Euler angles etc.

For calculations I am using GLM, if that makes any difference, although I don't think it should do.

The code that handles the updating of the Horde3D node is as follows:

btTransform trans;

sphere_body->getMotionState()->getWorldTransform(trans);

// getOrigin() returns the absolute coordinates, so I am keeping
// track of them to make sure I translate the correct amount
glm::vec3 sphere_cur_pos = glm::vec3(
    trans.getOrigin().getX(),
    trans.getOrigin().getY(),
    trans.getOrigin().getZ()
);

glm::mat4 sphere_node_matrix, matrix_t, matrix_r;

const float *matrix_floats;
h3dGetNodeTransMats(sphere_node, 0, &matrix_floats);

sphere_node_matrix = glm::make_mat4(matrix_floats);

matrix_t = glm::translate(
    sphere_node_matrix,
    sphere_cur_pos - sphere_last_pos
);

// sphere_last_pos is declared earlier in the code
sphere_last_pos = sphere_cur_pos;

btQuaternion quat = trans.getRotation();

matrix_r = glm::rotate(
    matrix_t,
    quat.getAngle(),
    glm::vec3(quat.getAxis().getX(), quat.getAxis().getY(), quat.getAxis().getZ())
);

h3dSetNodeTransMat(sphere_node, glm::value_ptr(matrix_r));

The above code produces the behaviour you can see in the YouTube video.

If I remove the rotation matrix and just use:

h3dSetNodeTransMat(sphere_node, glm::value_ptr(matrix_t));

then everything works fine and the sphere node stays in sync with the Bullet Physics wireframe, but there is of course then, there is no rotation.

Can somebody point out what I am doing wrong?

If any more information is needed just let me know and I will update the question.


texts: Dynamically added gameobject didn't show on canvas

texts:
I have a canvas with a Scroll View in it.

When I manually add a prefab under the Content, it showed up nicely.

But when I add it through the following code, nothing showed up!

GameObject RaceGO = (GameObject)Instantiate(Resources.Load("Race"));
RaceGO.transform.SetParent(Content);

Could somebody please tell me why!?

Much appreciated!

PS. I had checked that the gameobject IS in the content! I just can't see it!


texts:
Alright, so I've tried everything I can think of. I've put in over 10 hours into this crap, but nothing seems to work (tried multiple online tutorials as well). Always purple screen.

Here is the simple .fx code:

float4x4 matrixTransform;

struct VShader
{
    float2 Coords : TEXCOORD0;
    float4 Position : POSITION;
};
struct PShader
{
    float2 Coords : TEXCOORD0;
};

VShader VertexShaderFunction(VShader input)
{
    VShader output;

    output.Position = mul(input.Position, matrixTransform);
    output.Coords = input.Coords;

    return output;
}

float4 PixelShaderFunction(PShader input) : COLOR0
{

    return tex2D(textureSampler, input.Coords);
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader = compile ps_3_0 PixelShaderFunction();
    }
}

Here is how I'm assigning MatrixTransform:

Matrix Projection = Matrix.CreateOrthographic(GameSettings.VectorResolution.X, GameSettings.VectorResolution.Y, -1, 1);

Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
Projection = halfPixelOffset * Projection;

x.Parameters["matrixTransform"].SetValue(camera.Projection);

Note: the above code works just fine when the vertex shader is disabled. Everything displays like normal.

I'd appreciate it if someone could point out what I'm doing wrong.

Thanks.

EDIT:

I'm currently using multiple shaders in my code that do not use a vertex shader (pixel shaders). I am also making use of render targets. This leads me to believe there is something wrong with the vertex shader code, not the render targets.

EDIT 2:

public Matrix World { get; protected set; }
public Matrix Projection { get; protected set; }
public Matrix View(Vector2 parallax)
{
    return Matrix.CreateTranslation(new Vector3(-Position * parallax, 0.0f)) *
        Matrix.CreateTranslation(new Vector3(-Origin, 0.0f)) *
        Matrix.CreateRotationZ(Rotation) *
        Matrix.CreateScale(Zoom, Zoom, 1) *
        Matrix.CreateTranslation(new Vector3(Origin, 0.0f));
}

public void ReloadMatrices()
{
    World = Matrix.Invert(View(Vector2.One));
    Projection = Matrix.CreateOrthographic(GameSettings.VectorResolution.X, GameSettings.VectorResolution.Y, -1, 1);
    Matrix halfPixelOffset = Matrix.CreateTranslation(-0f, -0f, 0);
    Projection *= halfPixelOffset;
}

Zoom is 1f, Rotation always remains unchanged, and Origin is center of screen.


texts: Is it bad practice to add GameComponents and DrawableGameComponents outside of the main initialization method?

texts:
I'm working on a snake game that has multiple game objects (snakes, apples, obstacles), and game modes (classic, adventure), that are DrawableGameComponents. Is it OK that I'm adding them as needed instead of in the main initialization method?

If not, how should I go about drawing and updates components of my game that need to be added in other methods?

If yes, is there any way to get the initialization or load overridden methods to run? Or is making my own load method and calling it right after adding the component how it should be done?

Thanks!


texts: Is there a tool to import a sprite sheet into Flash as a frame-based animation?

texts:
I'm looking for a tool that can help create a Flash-based animation given a spritesheet -- basically the reverse of Spriteloq.

I'd like to take a sheet like the one below, import it into Flash, and then use Spriteloq (or a similar tool) to re-export as an optimized sheet that is compatible with the game engine I'd like to use -- instead of creating software that can read the specific sheet.


texts: The normal vector to a plane ax+by+cz+d=0?

texts:
I am calculating the normal vector to a plane ax+by+cz+d=0

According to the book:

The normal vector N is often normalized to unit length because in that case
the equation

d = N ⋅Q + D

gives the signed distance from the plane to an arbitrary point Q. If d = 0, then the
point Q lies in the plane. If d > 0, we say that the point Q lies on the positive side
of the plane since Q would be on the side in which the normal vector points.

How to get the N (Normal vector)? Thank you


texts: What do I need to reload after a device reset?

texts:
Is there a complete list of resources that need to be reloaded after a device reset? I want to make sure I'm not missing anything.

Also, should I reload them from disk each time, or do I want to make in-memory copies?


texts: Saving virtual goods balance in Android Game

texts:
I'm looking for a good way to store virtual goods and virtual currency balance in an Android game. Since these are "consumable" or "unmanaged" goods the balance is not backed up by Google and so there is a need for a solution that is:

Can't be hacked easily
Can easily be extended with additional goods and currencies
Survives application shut down and device boot


texts: Can i make a Game for play store on my own

texts:
I am not sure what i am asking for. Sorry if this question look stupid.

I love to play games on android and pc . Some times very cool  ideas strike me , but i don't know what to do with them. and they vanish over time.

I got no computer science background , since i am a math student . Although i learned C++ for a week for a exam. In short I know C++ but just the alphabets.

Is it possible that i can learn to make games. What should i have to learn.
Is it possible to learn from youtube. Since it's like side hobby i can give it few hours a day ( not money ).


texts: Grouping surfaces in pygame to get an object with two movement points

texts:
I would like to create a simple tank using pygame. One would drive the tank by controlling he velocities of two caterpillar tracks. They should be the two single movement points of the vehicle.

I'm looking for directions in which pygame methods and objects to check or tutorials regarding the topic.


texts: “Play Now” via website vs. download & install

texts:
I've spent some time looking over the various threads here on GDSE and also on the regular Stackoverflow site, and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on.

In particular, I'm talking about browser games vs. desktop games.

I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D (and also some synchronized/networked programming), but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now).

Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities* just so that a (possibly?) larger audience can be reached? Does it make sense to even go with a web-environment for the kind of game that I want to make? Does anyone have any experiences with decisions like this?

(* With the exception of Flash-based engines it seems like most of the other approaches have downsides when compared to what is available for desktop-based environments. I'd go with Flash, but I'm worried that Flash's 3D capabilities aren't mature enough right now to do what I want easily. There's also Unity3D, but I'm not sure how I feel about that at all. It seems highly polished, but requires a plugin to be downloaded for the game to be played -- at that rate I might as well have players download my game.)

For simple & short games the Newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "OK, I'm going to download and play that"?


texts: How to scale UV coordinates from a specific offset?

texts:
I'm currently attempting to copy a small texture onto a larger texture, but I want to have control over how large and at what UV position the smaller texture is copied over.

I've made some progress on this and can scale and offset the texture, but the issue is that the scaling is not from the center of the offset.

Does anyone have any ideas on how to do this?

---EDIT---

As you can see above, the capsule is at the center of the outlined box. When I scale the coordinates, you can see the red splotches representing where I'm standing scale towards the center/capsule. Now, to do this, the offset is set to (0.5, 0.5).

If I move the outlined box to the upper left corner, the offset no longer scales from the circle. It scales from the upper left corner with an offset of (0, 0). To get it to scale from the center, I need an offset of (0.125, 0.125) which is counter intuitive. I'm handling the offset and scaling manually, but I'd ideally like to automate the process and calculate it all based on position.

Here's the code I'm working with:

float2 newUV = i.uv - float2(_XMod, _YMod);
newUV = newUV.xy * float2(_ScaleX, _ScaleY) + float2(0.5f, 0.5f);


texts: How can I use GPL software like Stockfish Chess Engine in my Unity game?

texts:
I am working on a 3D Chess game and I want to implement an A.I bot to play with the player. I found a chess engine called Stockfish which serves this purpose, and I would like to implement that engine in my project.

Is it as simple as including the Stockfish code in my project or importing a binary as a plugin, or do I have to do something more complex because of the GPL licence?


texts:
OpenDota, A community driven platform for DotA 2 matches and players data is the best open-access API in gaming scene. I found no casual tutorial for using its API, So, I decided to make a one. Your feedback is welcome for inquiries or further improvements

Sincerely,


texts: Algorithm for optimal control on space ship using accelerometer input data

texts:
Does someone have a good algorithm for controlling a space ship in a vertical shooter game using acceleration data?

I have done a simple algorithm, but works very badly. I save an initial acceleration value (used to calibrate the movement according to the user's initial position) and I do subtract it from the current acceleration so I get a "calibrated" value. The problem is that basing the movement solely on relative acceleration has an effect of loss of sensitivity: certain movements are independent from the initial position.

Would anyone be able to share a a better solution? I am wondering if I should use/integrate also inputs from gyroscope hardware.

Here is my sample of code for a Cocos2d iOS game:

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    if (calibrationLayer.visible){
        [self evaluateCalibration:acceleration];
        initialAccelleration=acceleration;
        return;
    }

    if([self evaluatePause]){
        return;
    }

    ShooterScene * shooterScene = (ShooterScene *) [self parent];
    ShipEntity *playerSprite = [shooterScene playerShip];

    float accellerationtSensitivity = 0.5f;

    UIAccelerationValue xAccelleration = acceleration.x - initialAccelleration.x;
    UIAccelerationValue yAccelleration = acceleration.y - initialAccelleration.y;

    if(xAccelleration > 0.05 || xAccelleration < -0.05) {
        [playerSprite setPosition:CGPointMake(playerSprite.position.x +  xAccelleration * 80, playerSprite.position.y + yAccelleration * 80)];
    }
    else if(yAccelleration > 0.05 || yAccelleration < -0.05)
    {
        [playerSprite setPosition:CGPointMake(playerSprite.position.x +  xAccelleration * 80, playerSprite.position.y + yAccelleration * 80)];
    }

}


texts:
I'm looking to add circle-polygon collisions to my Separating Axis Theorem collision detection.

The metanet software tutorial (http://www.metanetsoftware.com/technique/tutorialA.html#section3) on SAT, which I discovered in the answer to a question I found when searching, talks about voronoi regions.

I'm having trouble finding material on how I would calculate these regions for an arbitrary convex polygon and also how I would determine if a point is in one + which.

The tutorial does contain source code but it's a .fla and I don't have Flash unfortunately.


texts: Deserializing component array using JSON

texts:
I have a collection of serialized components in JSON format:

{
    "components": [{
        "class": "com.package.component.PositionComponent",
        "x": 100,
        "y": 100
    }, {
        "class": "com.package.component.VelocityComponent",
        "x": 4,
        "y": 2
    }]
}

I want to load this into a collection of base Components in Java, specifically into an Entity. I am currently using YAML (parsed using SnakeYAML) to achieve this. The following file (which is virtually identical to the JSON one) is parsed and the components are stored in an ArrayList:

components:
- ==: com.package.component.PositionComponent
  x: 100
  y: 100
- ==: com.package.component.VelocityComponent
  x: 4
  y: 2

Is there any way I can achieve this using the JSON parsing facilities provided by LibGDX? I am currently using the following code to parse the components, but I have no idea how to get it to construct the correct appropriate object for each component:

JsonReader reader = new JsonReader();
JsonValue base = reader.parse("components.json");

for (JsonValue component : base.get("components")) {
    System.out.println(component.getString("class"));
}


texts: This may be a may be a very basic question but I have a 32x32 tile of grass for a 2D platformer I'm making. Is there an easy way to duplicate the tiles and lay them out? or will I have to copy and paste the tile a 100 times and adjust each one individually just to make a level?


texts:
I would like to know the flow for making modern 2D game artwork.

How are the assets made nowadays? Bitmap? Vector-based? Hand-drawn and painted? Drawn digitally? Modeled in 3D and exported to bitmaps?

I would like some information on programs as well, for fine looking art.
Why does Flash's vector art style look good in most games? How do I make equivalent graphics with external tools? Or equaly good and not vector-based, anyway.

Any special hints for animating?

An answer oriented towards a one-man-army indie developer with little experience but some artistic sense would be appreciated! Not a complete dummy with paint programs, but also not a master at all, just need efficient ways to achieve results.

Thanks.

NOTE: Pixel art is not the goal of this question, nothing related to direct pixel manipulation should be brought up here, but you're free to do exactly that :)


texts: Detecting collisions with a wall before Update

texts:
I'm making a script in unity to control (movement) a character in 3rd person and 3D space.

For that I'm using the CharacterController component.

All pretty standard: inside the update method a Vector3 which will be passed to CharacterController.move is crafted based on the input and collisions, movement and jumping are perfectly fine but I ran into an issue when trying to make a wall jump.

There are 3 steps involved in this:

Get the wall to jump of.
Check if the player pres the jump button.
Move the player in the desired direction.

An this is how I'm doing it:

void OnControllerColliderHit(ControllerColliderHit hit) {
   if(mController.collisionFlags==CollisionFlags.Sides) {
       //Get wall normal
       wallNormal=hit.normal;
       isOnAWall=true;
   }
}

Now inside Update

if(Input.GetButtonDown("Jump")&isOnAWall) {
    //jump...
}

And this work fine in most cases but only if player is giving input or last wall has a similar normal as current so obviously the normal isn't refreshing properly, but why?

Well, after some testing, I discovered that the OnControllerColliderHitis called after the Update method, and this is what I think is happening:

Physics engine detect the collision and stops the player
Update method not having any input just send it downwards
The OnControllerColliderHit method is not triggered(this part I am
sure)

Are my conclusions correct?

How can I fix this? (make the player jump without need to move the stick and just with the button)


texts: How do I implement references or relations for entities within a serialized savegame?

texts:
I have a 2D tile based RPG for which I'm developing save game function. In particular, I'm trying to save this structure:

A caster can have multiple buffs that he maintains. Each buff can have multiple effects applied to players or monsters. The pattern has links both ways (caster has buff, buff knows who cast it)

If I serialize caster, buffs and effects, how can i restore the relationship:
caster - buff - effect - target?

Would I need to implement something like unique identifiers for monster, buffs and players and then link them all together once the save game is loaded?


texts: Android OpenGL and non premultiplied textures

texts:
As I understand it; by default all bitmaps will will get the alpha channel premultiplied in Android if loaded using BitmapFactory.

My setup:
I have a 32bit bitmap(.bmp) where the alpha channel has a gloss map and the rgb is a specular map.

Issue:
I found out that I can load the bitmap without being premultiplied using the bitmap option:

opts.inPremultiplied = false;

Result:
When I render the alpha channel of the texture like this in the shader:

gl_FragColor.rgb = vec3(texture.a);

The resulting mesh is all white and not shades of gray as expected.

I upload the texture with this method:

GLUtils.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image, 0);

I have also tried using this approach

GLES20.glteximage

as well with the same result although I might have done something wrong there.

Can anyone spot where I have gone wrong or what else I need to do?


texts: Rotating, moving and scaling a mask in a shader

texts:
I want to rotate, move or scale a mask in a shader. But I have no clue to how perform these actions.

My code:

@Override
public void create() {
batch = new SpriteBatch();

background = new Texture(Gdx.files.internal("images/background.png"));
spritebackgournd = new Sprite(background,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());

foreground = new Texture(Gdx.files.internal("images/foreground.png"));
mask = new Texture(Gdx.files.internal("images/mask.png"));

 spriteforegournd = new Sprite(foreground,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());

shader = new ShaderProgram(Gdx.files.internal("shaders/shader1.vert"), Gdx.files.internal("shaders/shader1.frag"));
}

@Override
public void render() {

batch.begin();
spritebackgournd.draw(batch);
 batch.setShader(shader);
    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
    spriteforegournd.getTexture().bind(0);
    //texture.bind(0);
    shader.setUniformi("u_texture", 0);
    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE1);
    //spritemask.getTexture().bind(1);
    mask.bind(1);
    shader.setUniformi("u_mask", 1);
    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
    spriteforegournd.draw(batch);
    batch.end();
    batch.setShader(null);
   }

The vertex shader:

attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec2 v_texCoords;

void main() {
v_texCoords = a_texCoord0;
gl_Position = u_projTrans * a_position;
}

The fragment shader:

varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform sampler2D u_mask;
uniform mat4 u_projTrans;

void main() {
vec4 texColor = texture2D(u_texture, v_texCoords);
vec4 maskColor = texture2D(u_mask, v_texCoords);

gl_FragColor = texColor * maskColor.a;
}

What I would like to be able to is to scale, rotate and move the mask in the shader. How can I do this?


texts: Skybox: OpenGL texCUBE vs a textured cube

texts:
In OpenGL, the typical way that I've seen to set up a skybox using cubemapping is to create a cube in camera space, prepare a cubemap sampler with the appropriate six-sided texture, and then in the pixel shader use the camera space direction of the pixel as the input to texCUBE.
What I'm wondering is, if instead of this, I set up the same cube, but then simply textured each face of the cube with the appropriate face of the cubemap texture, and then rendered the cube with a standard shader, would it achieve the same visual effect?


texts:
I have been trying to figure out why my player character crouches like this when I use inverse kinematics on it. I followed this tutorial:

https://docs.unity3d.com/Manual/InverseKinematics.html?_ga=2.157285243.1916573353.1569208906-694809292.1561053348

but then the weirdness in the picture above happens. What is going on?

In case It helps, I used makehuman to make the player model, and used its "Game Engine" rigging option.

EDIT: Here are some additional pictures after I remade the project:

I left look obj blank because all it does is makes the player's head look a certain direction.


texts: How do I make a gun alignment to camera matrix in OpenGL GLSL?

texts:
I am trying to program a FPS game with OpenGL.

I am using 3D eight the OpenGL 3.3 programmable pipeline.

I have a gun and a camera that I loaded.

When I load all of the assets for the game, I put everything int a 4x4 matrix, as it is compatible with the view matrix.

I set the corresponding matrix for the model equal to all the needed variables, then I use another variable that I defined in a header file to draw the actual model...

I did some searching because I do not have the code with me, and the closest I could find is learnopengl’s model loading tutorial as that is the most similar.

What I have tried;
I have tried multiplying the matrix for the gun’s world info, which I will call the model view matrix (such as position and scale) times the view matrix. I have also tried doing the same but multiplying the model view times the inverse of the normal view matrix.

I already set the guns position equal to the camera’a position, but when I run the application and try to move around, the gun still moves away from the camera.

I knew a way of how to fix this in OpenGL 1.1 by using glLoadIdentity, which is now deprecated with the core version of OpenGL 3.*.

When i try to set the two matrices equal, I get different results because the gun doesn’t move at all.

When I move the camera with the inverse of view times gun, it moves away from the camera...

I learned about the inverse matrix thing from here:
https://forums.khronos.org/showthread.php/81932

My matrixes are also set up the same. The gun model view * inverse(view matrix) has worked the best... this link is where I found it.


texts:
I'm working on a 3D gallery experience and I'm having some difficulties regarding directional and point baked lights.

When I build it for web with webgl, only global lights are rendered, but when my prefabs are triggered those rooms comes with the directional/point lights perfectly working, and all planes and lights have the same config... I have spend to much time trying to get them right or understanding why is this happening, any help would be appreciated.


texts: Do I need to learn any physics if I use a physics engine?

texts:
Complete novice out here. Of course I know basic physics like mass and inertia. I don't want to make an engine I just want to make a game and use a physics engine made by someone else.

Do I need to learn any physics if I plan to use a physics engine?


texts: How do I get players to say "no" when they are afraid of missing out on sidequests or XP?

texts:
In my RPG, I have a companion NPC who is overconfident in his abilities and lacks self-control. I wanted to create a few situations where the player needs to reign them in and tell them "no". One such situation basically boiled down to this:

Companion: Hey boss, I want to do this really stupid thing that will almost certainly make things harder for us down the road and possibly jeopardize our goal. Is that okay?
Player Choices:

Yes, go ahead!
No, don't do that!

My hypothesis was that the vast majority of playtesters would choose "No". To my surprise, the vast majority chose "Yes"! And then when the consequences played out and indeed made things worse, playtesters wanted to reload from an earlier save point and pick the other option (choosing "Yes" wasn't game-ending, but it did mean that a perfect outcome wasn't achievable).
When I asked the playtesters why they chose yes, they made it clear that they understood that saying yes was undesirable and saying no was desirable. They also weren't seeking a challenge or anything. Instead, the most common thing I heard was:

I was afraid that if I said "No", then I'd miss out on a sidequest or XP.

One of them even said that in other RPGs he played, the only way to get a 100% playthrough was to say yes at every opportunity, and so they assumed that was the case for mine.
I don't want players to assume that saying "yes" is always the right answer, and for now, I'd like to keep the situation of having to tell the NPC "no" every once in a while. But I don't know how to overcome these player expectations and their fear of missing out of content, especially without just flat out saying "this isn't like other games, you won't miss out if you say 'no'".
So how do I get players to say "no" when they are afraid of missing out on sidequests or XP?


texts: Unity 2019.2.5: Convert Mouse Rotate/Pan/Zoom camera to touch

texts:
I have a Unity C# script that uses the mouse to rotate/pan/zoom a camera around a scene with a main focal point (PC Build). It works very well for me, but I need to convert it for a kiosk touch screen (windows Surface Pro) and have had no luck modifying the script or finding answers. Would some kind soul please save me from this hell!

My current working mouse script is below.

Any assistance is GREATLY appreciated!

using System.Collections;
using System.Collections.Generic;

public class MouseOrbit : MonoBehaviour {
    public Transform target;
    public float maxOffsetDistance = 2000f;
    public float orbitSpeed = 15f;
    public float panSpeed = .5f;
    public float zoomSpeed = 10f;
    private Vector3 targetOffset = Vector3.zero;
    private Vector3 targetPosition;

    // Use this for initialization
    void Start() {
        if (target != null) transform.LookAt(target);
    }

    void Update() {
        targetPosition = target.position + targetOffset;

        if (target != null) {
            targetPosition = target.position + targetOffset;

            // Left Mouse to Orbit
            if (Input.GetMouseButton(0)) {
                transform.RotateAround(targetPosition, Vector3.up, Input.GetAxis("Mouse X") * orbitSpeed);
                float pitchAngle = Vector3.Angle(Vector3.up, transform.forward);
                float pitchDelta = -Input.GetAxis("Mouse Y") * orbitSpeed;
                float newAngle = Mathf.Clamp(pitchAngle + pitchDelta, 0f, 180f);
                pitchDelta = newAngle - pitchAngle;
                transform.RotateAround(targetPosition, transform.right, pitchDelta);
            }
            // Right Mouse To Pan
            if (Input.GetMouseButton(1)) {
                Vector3 offset = transform.right * -Input.GetAxis("Mouse X") * panSpeed + transform.up * -Input.GetAxis("Mouse Y") * panSpeed;
                Vector3 newTargetOffset = Vector3.ClampMagnitude(targetOffset + offset, maxOffsetDistance);
                transform.position += newTargetOffset - targetOffset;
                targetOffset = newTargetOffset;
            }

            // Scroll to Zoom
            transform.position += transform.forward * Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;

        }
    }
}// CLASS ```


texts: How do I letterbox a C#/Monogame viewport within a resizeable window?

texts:
I am making a 2d game with xna/monogame. I want the main view area to always show 15x15 tiles, or 480x480px.

I've got something that sort of works, following this guide. It expands the view range if you make the window smaller. However, it works somewhat properly if you expand it. It works as intended if the window is maximized.

I want the range of what is rendered to be no larger than 480px x 480px regardless of the the window's size, but I'd like the sprites to appear bigger if the window resolution is set larger (and conversely).


texts: How can I repeat a Texture Region in libGDX

texts:
I have a texture that is part of a sprite sheet. I want draw the texture to cover a certain length, but I want it to repeat not stretch. However,when I use the following code

batch.draw(hillBottom, hill1.getX(), hill1.getY(), hill1.getWidth(), hill1.getHeight(), 0, 0, 1, hill1.getNumBlocks());

I receive an error indicating that the first argument must be a Texture not a Texture Region. I am new to game development, but I have read from multiple different guides that loading seperate textures in a game hinders performance which is why it should only be done if completely necessary. Is there anyway I can repeat the Texture Region?


texts: How to deal with references to shared manager classes

texts:
I am using C# with MonoGame, although this is relevant for any object-oriented programming language
Static classes should be reserved for stateless utility classes (for example System.Math) and they should generally be avoided along with singletons for manager-like classes. The reason for this is it prevents object-oriented strategies and may be under the false pretense that there is only one instance required at all times.
To solve these issues you could have instances like AudioManager, EffectManager, Time, etc. in a single global static object. But this does not solve another issue which is you do not control who has access to these instances. So instead pass in these instances from the top down through constructors to classes who need to access certain things.
In my game I have an entity component system. Character derives from Actor which derives from Component which is contained within an Entity. When a Character gets hit I want time to stop briefly (Time instance), the camera should shake (Camera instance), he should flash white (Effects instance), Damage text should be spawned (FloatingText instance) and a sound effect should be emitted (AudioManager instance).
This is just one example and child classes may need more things or pass in different parameters to these instances. Additionally, anyone higher up the hierarchy will need more instance references if they need to pass it down to someone who is lower down.
Q: "What is the problem in that?" A: "It is cumbersome and I am modifying an entire hierarchy when I want to change something one place"
If I realize a component needs a reference to another instance I need to modify the code throughout the entire hierarchy. A solution is to make the global static object itself a non-static instance and pass down the whole thing to all components (but I might only pass down a certain instance to other parts of the game).
"Maybe you just have a coupling problem? Character should not be the one to stop time, shake camera, etc."
Okay, who should then? I could use an OnHit event in Character and let AudioManager for example hook up to that for all characters and play a sound effect with different parameters depending on the type of Character. But now I need to make a switch statement on type inside AudioManager, not very object-oriented. Instead, I could have one request manager instance to all of these things that takes in a parameter list as well. But what is the difference between this and a shared object instance? Anyone with a reference to request manager can make any request it's just a bit more indirect.
Passing in a container to all shared instances in the constructor of e.g. Component seems like the best compromise. What do you think?


texts:
I am making a 2D RPG game in Monogame XNA. For the moment I have 2 kinds of data in my game: sprites objects and tiles.
All the sprites are contained in a array list. I iterate over the sprites ArrayList to update and draw each sprites. Sprites objects are sort by their Y positions before each draw. This way, my character and other enemies can walk behind sprites. Sprites can be anything that require player interaction for example: chest, tree, enemy, player…
Tiles represent inanimate objects(2D array) (object that you cannot interact with) and only used for collision data and have a basic animation system.
However, for sprites collision checking I have to iterate over every sprites to do a bounding box overlap check.
My system works well, but I want to simplify things. What if I store static objects in my 2D tile array? I could just do getTile(x,y) to get the object stored in that position instead of going through my array list.
In the future I would like to have several types of objects, weapons, projectiles, and I want a consistent way to organize this.


texts: How to stop SDL from freezing the rendering while resizing the window?

texts:
I have a simple SDL application with a re-sizeable window. If I minimize it and then maximize the window the rendering freezes. I've included a simple code example below which makes the screen flash through varying shades of grey. Try minimizing and then maximizing the window, and you can see that the rendering halts while the window is resizing. How do I stop the rendering freezing when going from minimized to maximized?

//FLASHING SCREEN CODE
//Demonstrates screen freeze when you minimise then maximise the screen....

#include "SDL.h"

using namespace std;

int main( int argc, char* args[] )
{
    //Initialise SDL2, declare Window + Renderer
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ); //Initialize SDL for video and audio
    SDL_Window* pWindow = NULL;
    SDL_Renderer* pRenderer = NULL;
    pWindow = SDL_CreateWindow("Minimise Maximise Test", 50, 50, 1200, 600, SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED);
    pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_TARGETTEXTURE);

    //The Screen colour which is going to flash through different shades of grey
    SDL_Color screenColour = {0, 0, 0};

    //SDL event for detecting X-out (quit)
    SDL_Event event;
    bool quit = false;

    //Loop
    while( quit == false )   //While SDL has not been X'ed out
    {
        //Handle quit
        if (SDL_PollEvent(&event) != 0)
        {
            if(event.type == SDL_QUIT) quit = true; //Press X-out to quit (but not visible on fullscreen)
        }

        //Make screen flash by changing its colour through shades of grey
        screenColour.r++;
        screenColour.g++;
        screenColour.b++;

        //Render the screen
        SDL_SetRenderDrawColor(pRenderer, screenColour.r, screenColour.g, screenColour.b, 255);
        SDL_RenderFillRect(pRenderer, NULL);
        SDL_RenderPresent(pRenderer); //like SDL_flip
    }

    //Shutdown
    SDL_DestroyRenderer(pRenderer);
    SDL_DestroyWindow(pWindow);
    SDL_Quit();

    return 0;
}

I'm currently running SDL2.0 v 2.0.3 on Windows 10 machine (experienced the same problem running on previous Windows 7 machine).


texts:
I'm currently facing some problems with sprites/images on different screen sizes. For now the game stage is stretched to maximum width and height of the screen.

In Samsung Galaxy S2, SGS3 and SGS4 the game is working as normal as expected:

But... yesterday I tested it on GT-P5110 android tablet.. and the result was:

The screen background and car sprite was replaced by black rectangles...

Does somebody know what's happening?

The same result occurs on sgs2/sgs3/sgs4 when any of the sprite image has more than ~4100px of height. Maybe it's something with image limits? If yes... how to know that limit? Currently (working on sgs2, but not on tablet) the background image size is 3117x480. It's so wide because it used for parallax background. If it exceeds the limit how should I handle this (join two images)?


texts: How do you prepare for out of memory conditions?

texts:
This can be easy for games with well defined scope, but the question is about sandbox games, where the player is allowed to create and build anything.

Possible techniques:

Use memory pools with upper limit.
Delete objects that are no longer needed periodically.
Allocate extra amount of memory at the beginning so it can be freed
later as a recovery mechanism. I would say around 2-4 MBs.

This is more likely to happen in mobile/console platforms where memory is usually limited unlike your 16 GB PC. I am assuming you have full control over memory allocation/deallocation and no garbage collection involved. That's why am tagging this as C++.

Please note that I am not talking about Effective C++ Item 7 "Be prepared for out-of-memory conditions", even though it's relevant, I would like to see an answer more related to game development, where you usually have more control over what's happening.

To summarize the question , how do you prepare for out of memory conditions for sandbox games, when you are targeting a platform with limited memory console/mobile ?


texts: I have created a day and nigh cycle in a game of mine by drawing a rectangle over the screen and having it's alpha change constantly. However, I obviously want to add some lighting to the game. Is there a way to kind of set the alpha of a particular part of a rectangle to 0 using pygame? Or is there perhaps another way of going about this whole lighting thing?


texts: Frame rate independent gameplay implementation in pure Java

texts:
I've been looking up on FPS independent movement recently, and I somewhat understand the concept. But I'm having trouble implementing it in pure Java.

Any one have any idea of how I could implement is as well as abstract it in its own class such as "Time" class?

So, I tried implementing the suggestions in my game loop. but even though i am getting steady 60 FPS, my "deltaTime" has values of around 0.6 - 0.9, but for 60 FPS it should be 0.01 !

What is going wrong here?
Should I calculate "deltaTime" at 1 or 2?

Code :

long lastTime = System.nanoTime();
    double delta = 0.0;
    double ns = 1000000000.0 / 60.0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;

        // 1

        deltaTime = ((now - lastTime) / 1000000d);

        lastTime = now;

        if (delta >= 1.0) {

            // 2 :
            System.out.println(deltaTime);

            update();
            updates++;
            delta--;
        }
        render();
        frames++;
        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            //System.out.println(updates + " ups, " + frames + " fps");
            updates = 0;
            frames = 0;
        }
        if (glfwWindowShouldClose(window))
            running = false;
    }


texts: The most popular Resolutions and Aspect Ratios in Android OS 2019

texts:
I develop the game with Libgdx framework. When I tried to deal with support multiple screen resolutions it turns out that Libgdx is not following Android approach how to deal with Screen sizes and densities (mdpi, hdpi, xhdpi, etc folders).

I found only one way to handle assets - ResolutionFileResolver.
I have to create folders with different resolutions and the Libgdx choose more appropriate texture for me automatically for each device.

Android platform has a huge amount of Phones and Tables with different screen resolutions. I have to find a good strategy on how to handle it.

For example let's take a look at the case where I have 2 folders in my game: "800x480" and "1440x2560". The device on which I run the game has "1280x720". In this case, "800x480" resolution will be chosen as more appropriate. It leads to bad quality of the Textures because of stretching.
At the same time, I can't leave only one asset with high quality. It leads to cut all older devices with a small amount of RAM.

The idea is to create 3 most popular resolutions for 3 categories:
low, middle and high resolutions.

Where can I find some statistic about the resolutions popularity of Android Devices? I know about the Android Developer Dashboard but it doesn't show Screen Resolutions.
Does anyone use Libgdx in 2019? How to deal with Multiple Screen Support in this framework?
Any real statistic about the most popular Aspect Ratio? Which aspect ratio you choose as "basic" in your games?

I would love to see any "best practice" how to cover as many devices as possible with the good quality of the view.


texts: How to properly simulate object aproximation towards camera in 2D?

texts:
I'm trying to make some objects come towards the camera but it just doesn't feel right... you can check the progress here:

http://testing.fyrastudio.com/lab/tweetOlympics/v0.005/

You run by repeateadly hitting the letter Q, and around position 700 the first hurdle appears. But it just doesn't look right. I think that on real life, the hurdle would go slower when it's further away, and when it's closer to the camera, it would go real fast... and now it's doing it the other way around...

Here's the code handling the hurdle movement:

hurdle.scaleX = hurdle.scaleY = (athlete.position - hurdle.position_initial) / 1000;
hurdle.y = bg.image.y + (athlete.position - hurdle.position_initial) * 0.4;

Any ideas??
Thanks!!


texts:
How to setup the rendering and camera for isometric gameworld projection? And specifically how do i get the images exactly the right size?

What angles to use to get the exact 2/1 isomtric view?
Methods to set the camera on the right position?
Options to set like anti alias off.

I have tried many things, 45, 30, 35.264 degree angles. What i do is set the angle of the camera, then place the camera in front of the model then use dolly/fov/lens settings to get the left and right edge of the model lined up with the save frame. Then adjust camera height so the bottom lines up with the bottom of the save frame. But i keep getting jagged edges and not the isometric style 2 width one height.


texts: Are the first three values that describe a 3D plane actually a 3D vector?

texts: A 3d plane is typically defined as a,b,c,d. Are a,b,c actually the x,y,z coordinates of a 3d vector, with d defining the rotation of the plane, something like axis-angle rotation data?


texts: Where to put graphic representation of game entity?

texts:
I am working on simple 3D version of Snake game. I created classes like snake and grid so far. My concern is, putting all render logic (draws cubes - to show snake, and lines to show the grid) in above class could obscure the "pure" logic which should be divided from "view" layer.

So my question is, how to handle the whole render layer, separately from entity objects?

My current idea is to add object of "renderer" to each class which will encapsulate whole canvas work inside. There will be also master-renderer always looking for renderer inside all entities.

PS. I use JavaScript and Three.js


texts: How can I transmit move information from player to player in a web application?

texts: I am trying to create an online chess game using ActionScript and Flex.  It works well when I have two players on the same PC, but I want to publish it as a web app.  How can I transmit a move or action from one user to another, such that the other user sees what the first one did?


texts: How to simulate a liquid like "The Cook" or "Bake it"?

texts: I want to make a simple liquid something like these gifs:


texts:
Working with an infinite set of cubes, is there a way of detecting which cubes exist within a frustum?

Most frustum culling seems to work along the lines of running through all objects and seeing if they intersect - this is ok with a finite set of objects, or something like Octrees.

I'm currently finding all cubes within the frustum's bounding box - but that's far more than I really need.

I could then test these all against it, but I was wondering if I could skip a step.


texts:
I have a problem at the moment when I draw some models to teach me more about 3D game programming. The models at the moment overlaps each other from some angles witch makes sense since the game at the moment draws from left to right, line after line.

However my question is: Is there any easy escape from this issue or is there any way that you could draw the in-game world from the players position?

I would really appreciate if someone could give me some answers on this.


texts:
I want to replace a vertex buffer with another completely different vertex buffer, different size and values, it will not get replaced every frame.

gl.deleteBuffer(vertexBuffer);
vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vArray, gl.STATIC_DRAW);

I am using that code to replace it, I don't think it is the correct way because I am getting:

GL ERROR :GL_INVALID_OPERATION : glDrawArrays: attempt to render with no buffer attached to enabled attribute 1

I don't know if this is related to the error but I am rendering using the vertex buffer when I replace it.


texts:
In my game I have a world with randomly generated islands.
My islands are based on the pixel information of the LibGDX Pixmap class.

Now I need to rotate the islands. For this I need to rotate the Pixmaps. Not for drawing, but for reading the pixel data of the rotated Pixmap afterwards.

My problem is, that I don't know how to rotate the Pixmap, so I can read the pixel data of the rotated Pixmap.

Drawing a rotated Pixmap works well, but I need the rotated data persisted, so I can read it.

My code I started with, which doesn't work:

public Pixmap rotatePixmap(Pixmap pixmap, int angle){
    Sprite sprite = new Sprite(new Texture(pixmap));
    sprite.setRotation(angle);
    return sprite.getTexture().getTextureData().consumePixmap();
}

How can I rotate the Pixmap, so the pixels are altered to the desired rotation?


texts: How to move an object up and down like a wave?

texts:
I am trying to move my object up and down using cos and sin, but I have problem understanding how does the sin and cos work, so I can make my object move up and down like a wave frequently

Init Time starts from value of 16.00  it keeps on increment up to 17.065

initTime += msec * 0.001;
float x  =  cos(initTime* 2.46) * 2075;
float y  =  sin (initTime* 2.888) * 200;

My object goes down and up, then goes back to its initial position, then goes up and down once again, I want it to be like a wave


texts: Unity 5: 3rd Person Controller runs by default. How to change this?

texts:
I have been working with the Third Person Controller of the Standard Assets (called Sample Assets in the beta versions) in Unity 5. When the player press the forward button, the character runs by default, and walks if you hold Left Shift, and I want to swap that.

However, The controller makes use of Blend Trees, and have two scripts to manage movement and input and it's far too complex for me and so I need your help. How can I change the controller so that the player walks by default and has to hold Shift to run?


texts: Unity sidescroller with 3D objects/environment. Should I create a 2D or 3D project?

texts:
I'm looking to make a side-scroller in which the camera and all objects can only move in the x and y directions.  However, I'm going to have all objects and environments as actual 3D models.

Is it better to create a 2D project and just use 3D models, or should I create a 3D project and mess with the scripts to only allow x/y movement of objects and the camera?

Or does it not really matter?


texts: How can the fluid stream be stuck to the top of flask?

texts:
I created a flask and added a fluid stream to the top of the flask. When I translate the flask, the fluid stream goes along with the top of the flask. How do I achieve this when rotation occurs.

   void Start () {
    aa.transform.position = new Vector3(bb.transform.position.x,
    bb.transform.position.y + 4, bb.transform.position.z);
    aa.SetActive(false);
    aa.SetActive(true);
   }

void Update () {
    aa.transform.position = new Vector3(bb.transform.position.x, bb.transform.position.y+4, bb.transform.position.z);
   //aa is the fluid stream and bb is the flask
    cc.transform.position = new Vector3(bb.transform.position.x, bb.transform.position.y + 4, bb.transform.position.z);
    }

The traslation works. But you can see the gap between top of flask and rotation here. How do I close that gap?


texts:
In the game I'm trying to code I got to have two bodies. One StaticBody and one DynamicBody. I want to have the DynamicBody on top of the StaticBody. Somehow all I get is this:

Is it possible that the viewports lower, left corner isn't at 0,0? And why can't the DynamicBody get on top of the StaticBody?


texts: How to make smooth 2-d zooming in Processing

texts:
I am making a 2d game with camera zooming using Processing. Currently, my program reduces the size of each block by one. This works very well when there are only a few blocks on-screen, but not when there are hundreds. The camera zooms out on an exponential scale, and looks very jittery.

I know that some game engines have systems to overcome this, by distorting some of the blocks, but I am making this game from scratch. I want to know if there is a different trick or system that will achieve a smoother zooming.


texts:
Exactly as the question says. Is there a way i can draw vertices only into the stencil buffer.

Basically i want to perform some operations on some vertices of a mesh and based on the result, draw passing vertices only onto the stencil buffer of the screen


texts:
Hi Im trying to move some 3D text on one axis, but for some reason it moves on 2 with this code. Can someone explain why this is/ how to fix it? Maybe this is a simple solution but i cant find it.

using UnityEngine;
using System.Collections;

public class MoveTitle : MonoBehaviour {

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

    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown("up") && ScrollDown == false)
        {
            transform.Translate(0.0f, -1.2f, 0.0f);
            ScrollDown = true;
        }
        if (Input.GetKeyUp ("up"))
        {
            ScrollDown = false;
        }
        if (Input.GetKeyDown("down") && ScrollDown == false)
        {
            transform.Translate(0.0f, 1.2f, 0.0f);
            ScrollDown = true;
        }
        if (Input.GetKeyUp ("down"))
        {
            ScrollDown = false;
        }
    }
}


texts: How can I restrict the rotation of an object to a subset of axes using quaternions?

texts:
I've got a question about quaternions in my WebGL application.

How can I rotate an object only around two axes? For example, how can I exclude/nullify rotation about the Y axis?

The problem is that when I rotate something around X axis, and then around Y axis, it rotates around Z axis slightly as well. I have read whole piles of posts about it (for example)  but none of them really helped me. Reversal order of multiplication operations doesn't work for me. My actual code below:

// Main rotation function:

rotateCamera: function(angleX, angleY) {
    if (angleY !== 0) {
        this.yawRotation.axisToQuaternion(angleY, this.tempVec.make(1, 0, 0)));
        this.rotation.multiply(this.yawRotation);
    }
    if (angleX !== 0) {
        this.pitchRotation.axisToQuaternion(angleX, this.tempVec.make(0, 1, 0)));
        this.rotation.multiply(this.pitchRotation);
    }
    this.rotation.normalize();

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());

// Matrix setRotation function:

setRotation: function(m) {
    this.element[0] = m.element[0];
    (... some code omitted ...)
    this.element[10] = m.element[10];
},

And the ought-to-be-working code based on other posts (which is not working):

rotateCamera: function(angleX, angleY) {
    if (angleY !== 0) {
        this.yawRotation.axisToQuaternion(angleY, this.tempVec.make(1, 0, 0));
    }
    if (angleX !== 0) {
        this.pitchRotation.axisToQuaternion(angleX, this.tempVec.make(0, 1, 0));
    }
    this.yawRotation.multiply(this.rotation);
    this.rotation.copy(this.yawRotation);
    this.rotation.multiply(this.pitchRotation);
    this.rotation.normalize();

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
},

EDIT: I have added more info about the actual code.

EDIT2: Okeeeey, I almost found a working answer for my problem (adapted it from Rick Hoskinson's post). My updated code below:

rotateCamera: function(radX, radY) {
    // Pitch (vertical rotation)
    if (radY !== 0) {
        this.pitch += radY;
        // Prevent camera from flipping upside-down (constrained by vertical "plane")
        this.pitch = Math.clamp(this.pitch, -Math.PI/2, Math.PI/2);

        this.rotation.axisToQuaternion(this.yaw, this.tempVec.make(0, 1, 0));
        this.rotation.multiply(this.tempQuat.axisToQuaternion(this.pitch, this.tempVec.make(1, 0, 0)));
    }
    // Yaw (horizontal rotation)
    if (radX !== 0) {
        this.yaw += radX;

        this.rotation.axisToQuaternion(this.yaw, this.tempVec.make(0, 1, 0));
        this.rotation.multiply(this.tempQuat.axisToQuaternion(this.pitch, this.tempVec.make(1, 0, 0)));
    }

    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
}

Camera's roll has been eliminated using this method, but strange camera motion appears when rotating from one of the sides and then looking below (or I should say trying to look below, cause it curves away from this direction).


texts:
I'm writing my first game. It's an adventure-RPG in the style of Starflight. I'm thinking about how to represent game state. There are three obvious parts of game state: dialog, combat, and story/quest.

I could have three separate data structures, but some state elements don't fall clearly into a single jurisdiction. For example, maybe a quest requires that you damage several ships without destroying them. Quest directives are generally story elements, and ship damage is an element of combat, so in this case a collection of combat elements is equivalent to a story element.

You might suggest a workaround where the quest element is separate, and isn't updated until combat ends. This is limited, though. What if a particular ship is supposed to spawn during combat once the quest directive is met? Now you have a dependence between elements in two different data structures -- elements that represent essentially the same piece of information.

This might lead me to a use a monolithic structure that houses all state elements, but intuitively this strikes me as sloppy and error-prone.

So how is it generally done?


texts: Any social gaming services for JavaScript games?

texts:
I'm currently planning on building a HTML5/JavaScript game for the various platforms (Browser, iOS, Android, and WinMo7). I, obviously, would like there to be simple multiplayer (1v1, asynch), leaderboards, etc.

Finding a service that provides this for native applications is easy (Scoreloop, Gree, etc.) but I have yet to find one that allows access through JavaScript. So with that said, does such a service/platform exist or am I looking at creating my own (probably with node)?


texts: What sprite Resolution did 16-Bit Games use?

texts: I am making a new 16-Bit Styled game and I was wondering what the most common sprite resolution is for 16-Bit Systems.


texts: How to cache the main camera as a global variable?

texts:
I want to create a utility class that will, among other things, return a cached reference to the main camera. Is the below code correct? My concern is that I'm doing it wrong and that FindGameObjectWithTag is being called each and every time the getter is referenced.

using UnityEngine;

public static class Utils
{
    public static Camera MainCamera { get; } = Camera.main;

}