texts: How to change the color of an invalid texture?

texts:
In openGL, when I don't bind a texture, or I bind a texture that was loaded incorrectly, any calls to texture2D/texelFetch in the shader will return vec4(0, 0, 0, 1), is there a way to change this to return vec4(1, 1, 1, 1) instead?

Initially I looked for a way to test if the sampler2D was valid, and when I couldn't find that I tried using glColor4f, but that doesn't seem to work either--although that could be the amdgpu driver, it seems to have some trouble with the old pipeline calls generally.

Is there someway to change what this default return color is?


texts:
A few years back it was looking like COLLADA was going to be quite a big thing, maybe at last a fairly standardized format for getting 3D assets from a DCC package into the tools pipeline of a game. And it looked like a good option for an indie developer that didn't want to lock themselves into a single 3D package by writing custom export plugins.

But I've not heard much about it recently. And Feeling Software, who had supported the format with their Max/Maya exporters and FCollada lib appear to have withdrawn any free versions of those tools.

Is COLLADA seeing much use these days? Are there any free/inexpensive libs/tools to assist in dealing with the format, or are people just reading the raw XML themselves?

Or is there a better option these days - say for an indie developer that wants to get models/animation from potentially Max, Maya, or Blender into their engine? - FBX? Something else?


texts: Blurry text in Unity UI at default scale

texts:
I'm working on a VR (GoogleVR Cardboard) game, and need to include UI elements within it.

Ever since I first learned how to use Unity's UI elements, I've been limping around what seems to be a major problem: at the default (1,1,1) scale, literally everything involving fonts that I add to a world-space Canvas ends up looking like scaled, blurry bitmaps.

I can kludge around the problem by manually changing the scale of everything UI-related to (0.1, 0.1, 0.1) and multiplying the dimensions of everything by 10... but I can't believe this is how Unity's UI editing is intended to work by design.

Somewhere along the line, I must have overlooked something major. The question is... what? Is there an option somewhere to either make Unity render fonts at a higher resolution, or to at least change the default scale for new items from (1,1,1) to (0.1, 0.1, 0.1) & multiply all the default dimensions for new UI items by 10?


texts:
I have seen the document for libgdx and managed to move the character and also to implement bounds but the document does not show how to implement jumping.

I have downloaded the superjumper demo code but it is too confusing for me.
Is there anyone here who can guide me?

Say for example we have a spritebatch:

Spritebatch batch;

How can I implement a jump for this spritebatch when the screen is touched?


texts: What is an efficient way to get a look-at direction from either a quaternion or a transformation matrix?

texts: So, I have an object in my custom engine (C++), with a column-major transform in world space. I'm using a package that takes a look-at direction as an input. What's the most efficient way to get a look-at direction from this transform? Do I extract the rotation matrix? Do I try to extract a quaternion?


texts: How do I make UIText scale properly in a VerticalLayoutGroup in Unity?

texts:
I have a Panel with an AspectRatioFitter on it.

In there, I have a vertical layout group, with three buttons, Standard Mode, Speed Mode, Chaos Mode.

I have the Layout Group's anchors set to keep its size relative to the parent Panel.

The problem is that the text doesn't resize when I change the screen resolution. You can see it's cut off to say "Standard M" in the bottom image.

But if I say "Best Fit", the texts aren't the same size, because the boxes are big enough to allow the shorter text to be bigger. The only way I've been able to fix this is to adjust the sizes and anchors of the text boxes by hand. Is there an automatic way to do this?


texts:
I want to make a terrain for a RPG game that I'm developing. I started modeling the surface and implementing it to my game, but now I realized that i might be doing everything wrong. So I would like to ask a few questions:

How should I make the surface Model?

I'm developing my game without an engine, so I have to do coding for everything (Java, LWJGL). I use Blender to model the surface, and I export it to an .smd model file.

How to detect intersections between the surface and other models?

I guess I need to detect intersections, to make the terrain walkable. The problem is that I don't know the best and easiest way to do that. I tried making a triangle-triangle intersection detection algorithm, but it was to hard for me, and I guess I need something faster and simpler.


texts: Software/Hardware options for game music

texts:
I have some friends who want to make the music for a game I'm developing. We have no idea where to start. I've seen software like Reason (way too expensive at $450). I've also seen stuff like GarageBand for $15. I'm happy to pay up to $50 for software, and I've seen some good quality free software like lmms. I just have no idea what each of them are good for. I'm also thinking of getting a cheap midi keyboard, since that'd be a million times easier than clicking a mouse trying to get the right notes in the right places. So,

1) What hardware is recommended for simple background music

2) What software is recommended for simple background music

3) Where can I direct my friends for learning more about music creation on a computer

I know that I'm being really general, and some people might want to know the "type" of music or what instruments will be used. I have no idea, so I'm just speaking basically.


texts: 2D animation example in pyglet (python) looping through 2 images/sprites every x seconds

texts:
Suppose you have two images: step1.png and step2.png .

Can anyone show me a very simple example in pyglet how to loop through those 2 images say every 0.5 seconds?

The character doesn't have to move, just a simple black screen with a fixed region wherein the two images continually change every 0.5 secs.

I know how to make a character move, shoot projectiles etc. but I just can't figure out how to control the looping speed of the images.


texts: OpenGL poor performace with instanced drawing

texts:
I'm just started learning OpenGL and this is my first project besides tutorials. I'm trying to load a huge enginering model:

The data is structured in a way that I thought I could use instancing for very good performance, because many items are simple primitives (cylinder, torus, cones, etc) with different transformation matrices. So I structured my data this way:

Primitive 1
  VAO
    VBO -> vertices
    VBO -> indices

    Instance 1.1
      VBO -> object color
      VBO -> transformation matrix

    Instance 1.2
      VBO -> object color
      VBO -> transformation matrix

    Instance 1.n
      VBO -> object color
      VBO -> transformation matrix

Primitive n
  VAO
    VBO -> vertices
    VBO -> indices

    Instance n.1
      VBO -> object color
      VBO -> transformation matrix

    Instance n.n
      VBO -> object color
      VBO -> transformation matrix

The model has ~50k unique primitives and ~120k instances, so in general each primitive has 2 instances. But in practice, some have 10 and some have only 1. I end up with 50k VAOs and then call dlDrawElementsInstanced for each VAO.

The model is being draw at only 3 fps. I gues it's because of the number of glDraw calls (50k for the triangles and 50k for the outlines). The shaders are very simple, not even lightning is being applied.

To be sure of that I changed the way I organize the buffers: I put everything in a single buffer, but to do that I had to pass the color and transformations matrices as vertex attributes to each vertex. I know this isn't right but I had to test if the problem was the number of glDraw calls. I couldn't even load the model this way because the buffers get way to big and I get out of memory. So I tested this theory on a smaller model that was taking 50ms to render in the instanced way. With a single VAO for everything and only a single glDrawElements call the model is taking less than 1ms to render.

I know that putting everything in a single VAO and passing the trasnformations for every vertex is not the correct way of doing this. Now I also know that instancing isn't the tool for this due the very few intances for each mesh. So the question is, what would be the correct way to setup the buffers to minimize the number of glDraw calls?

I think that it would be perfect to store all in a single VAO (so I could call glDrawElements a single time) but use something like the glVertexAttribDivisor used in instancing to inform the shaders when to use the next shaders. But not exactly because I had to manually inform when to use the next matrix, in way like glPrimitiveRestartIndex works.

I'm using OpenGL 3.3


texts:
My game has a 2-tier hierarchy of levels, it is composed of 6 or more "outer levels" that consist of 8 or more "inner levels". Reaching an inner level unlocks the next inner level. Reaching the top inner level of an outer level unlocks the next outer level. The first inner levels of an outer level resemble the inner levels of the previous outer level, but each outer level has more inner levels than its predecessor.

What terms are common to refer to "outer levels" and "inner levels" in such a situation? The game is very abstract, so something like "world" for the outer level would be inappropriate.


texts: How to select two different instances in Unity C#

texts:
I have 2 Balls, 2 Nodes, and 1 Hand. I can pick up a ball, send it to a Node, grab it, put it on another Node, but I can't grab any other balls.

The problem is that the Ball is defined publicly in The Node Manager. The Node Manager is a script given to The Hand and Each Node, because these are the places The Ball needs to go. While each Holding Place can easily declare itself, there is only one spot for a Ball. I can't add two Balls. I could make a Ball1 and a Ball2, but that's not very scalable.

What I'd like to do is find a way to get the name of the Ball being looked at and use that to power the Ball Selection instead of using a public declaration.

What I want to do is something like a Raycast, but I feel like I'm already using a Raycast by using Pointer Enter and Pointer Exit. When you look at the Balls, they use the Pointers to activate certain scripts like changing the colors of the Balls, and actually triggering the code to grab things. If I can do all that with the Event Triggers, I should be able to specify a Ball. But I can't find out how to do that.

Part of me thinks the code for grabbing the Ball with your Hand actually needs to be on the Balls themselves, and not the Hand, but as much as I try, I can't seem to figure it out. I am officially giving in and asking for help.

I'm working off of this tutorial. I sent the author a message and he said that he's Working On It and would get back to me, but it's been like two weeks. It seems like it should be a really easy fix, but then again, the whole thing is spaghetti code, so who knows.


texts: What engine is used in an introductory game-development course?

texts:
I am preparing a course in game-development. It is a choice-coures for 3rd-year students of computer science, who have working knowledge of several programming languages (C, C++, Java), algorithms, data structures etc. For the class and home exercises, I am considering two systems.

Initially, I thought of using Unreal Engine - since it is widely used in the industry, so using it will give the students an edge when looking for a job.

However, I then thought that such a complex engine might distract students from the design aspects of a game, and put them too much into the intricacies of graphics and animation. So I thought of using PyGame, which is much simpler.

My question is: what game-development engines are commonly used in similar courses (introductury GD courses for undergraduate CS students)?


texts: How do I scroll to follow my sprite in the physical world?

texts:
I am using andengine to make a game where a sprite (player) is going up across the stage,  and I want the camera to stay centred on the sprite the entire time.

This is my world so far:

final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager);
final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager);
final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);
final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);

final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);

/* Create two sprits and add it to the scene. */

this.mScene.setBackground(autoParallaxBackground);

this.mScene.attachChild(ground);
this.mScene.attachChild(roof);
this.mScene.attachChild(left);
this.mScene.attachChild(right);

this.mScene.registerUpdateHandler(this.mPhysicsWorld);

The problem is that when the sprite reaches the top wall, it crashes.
How can I fix this?


texts:
I created new project in libgdx without Android, specified for Eclipse. I added testcar.png to assests in core project, refreshed core and desktop projects,

new Texture(Gdx.files.absolute("C:\\TestGame\\desktop\\bin\\testcar.png"));
new Texture(Gdx.files.internal("testcar.png"));

gives

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException:

Couldn't load file: C:/TestGame/desktop/bin/testcar.png
    at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:148)
    at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98)
    at com.badlogic.gdx.graphics.Texture.(Texture.java:100)
    at com.badlogic.gdx.graphics.Texture.(Texture.java:92)
    at com.mygdx.screens.MainMenuScreen.show(MainMenuScreen.java:33)

but both those constructors work with jpg or gif(same folder as png) without any problem.

What i do wrong ? Is it bug?


texts: Is there a way to make money from indie downloadable games?

texts:
It appears that there are ways to make money with flash games through portal and aggregator sites and embedded ads.

But I do my programming in C and C++.  I've started a prototype which relies on a few existing C++ SDK's.  The game would have to be downloadable.   Is this just a labor of love, or are there any ways to make money from this type of game?  Does anyone pay for shareware anymore?  What other options are there?


texts: How can state changes be batched while adhering to opaque-front-to-back/alpha-blended-back-to-front?

texts:
This is a question I've never been able to find the answer to. Batching objects with similar states is a major performance gain when rendering many objects. However, I've been learned various rules when drawing objects in the game world.

Draw all opaque objects, front-to-back.
Draw all alpha-blended objects, back-to-front.

Some of the major parameters to batch by, as I understand it, are textures, vertex buffers, and index buffers. It seems that, as long as you are adhering to the above two rules, there's little to be done in regards to batching.

I see one possibility to batch, while still adhering to the above two rules. Opaque objects can still be drawn out of depth-order, because drawing them front-to-back is merely a fillrate optimization, meanwhile state changes may very well be far more expensive than the overdraw of drawing out of depth-order. However, non-opaque objects, those that require alpha-blending at least, must be drawn back-to-front in order to avoid rendering artifacts.

Is the loss of the fillrate optimization for opaques worth the state batching optimization?


texts: How do I reuse the same vertex data, but with different colors, for my sphere objects?

texts:
I'm using OpenGL to display a 3D network, with nodes represented as spheres (I haven't gotten to edges yet). I'm a total novice, and having a bit of trouble wrapping my head around OpenGL.

These networks need to be generated programmatically, so I've got a function that produces vertices for a sphere with radius 1 centred at the origin, and I'm translating and scaling it to produce each of the nodes in the network. I'm using glDrawElements() to draw my nodes, so I'm storing indices for the vertices of my sphere as well.

Once a network is produced, it doesn't change. The camera position can change, but nothing else will. My current strategy is the following:

When a network is generated, for each node, make a copy of the unit sphere, and apply the appropriate translation * scale matrix. Store all of the vertices (and associated colours) in a single array/VBO.
When drawing, set the scene-to-camera and perspective matrices to a uniform, then use a single glDrawElements() call to draw all my nodes.

So a couple of questions about this:

Since all my nodes are essentially identical, I could just store vertices for one sphere, and transform the sphere on the fly when I render the scene. There might be a lot of nodes, so this could save substantial memory. But each sphere has quite a different set of colours... is there a way to tell OpenGL to use an offset for the colour data but not the vertex data?
Assuming the answer to part 1 is no, would it be better to keep vertices for a single sphere in my VBO, and then substitute the colour data and draw each node with a separate call to glDrawElements()? Or is there some other solution that I'm not thinking of?


texts: Calculating the 2D edge normals of a triangle

texts:
What's a reliable way to calculate a 2D normal vector for each edge of a triangle, so that each normal is pointing outwards from the triangle?

To clarify, given any triangle - for each edge (e.g p2-p1), I need to calculate a 2D normal vector pointing away from the triangle at right angles to the edge (for simplicity we can assume that the points are being specified in an anti-clockwise direction).

I've coded a couple of hacky attempts, but I'm sure I'm overlooking some simple method and Google isn't being that helpful today - that and I haven't had my daily caffeine yet!


texts: I want to combine multiple Unity games in one Unity app (or other framework if necessary). This app would have a bunch of buttons that will start the desired game. Is this possible and what would be the best way to do this? Thanks!


texts: Unity3d webplayer failed to download data file

texts:
When testing my game web builds on localhost, I get the error "Failed to download data file". The game data file is correctly placed, and the page loads fine, it just wont download the plugin, or prompt me to do so.

I tried the following things:
Add MIME Types to IIS 7.5:

Open IIS Manager
Double click "MIME Types" in the IIS section.
Click Add on the right side "Actions" menu.
File name extension: = .unity3d
MIME type: application/unity3d
click ok
Restart the server (right side "Actions" menu)

That didn't work for me specifically because it turned out I was using IIS Express, so I did the following:

If Windows 7, browse to 'C:\Users\\Documents\IISExpress\config\' and open the file: ApplicationHost.config.

Search for 'staticContent' and add the following before the closing tag:

However, again, it didn't work..


texts: OnTriggerEnter With First Person Controller

texts:
I'm working on an FPS for my first time.

I'm creating a simple terrain and instatiating 15 cubes on my terrain. (This works fine). Each cube is named "cube" and has a static trigger collider.

Here's what my scene looks like:

When my first person controller collides with my cube (instantiated object) then I want the cube to deactivate and add 1 to my score, but nothing happens.

Code:  I added this code in FirstPersonController.cs

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.name == "cube")
    {

        other.gameObject.SetActive(false);
        // when the player touches my spawned object then I want to
        // deactivate my cube, but nothing happens

        Debug.Log("collidedwith:" + other.gameObject.name);

        score += 1;
        scoreText.text = score.ToString();

    }
}


texts: Clamp quaternion relative to plane normal

texts:
How would one be able to clamp a quaternion based on the angle relative to a plane surface (defined by a normal)?
My diagram below provides more of a visual explanation of exactly what I am talking about.
The quaternions are clamped based on the angle between the planes surface, and the quaternion's forward vector (i.e. q * (0, 0, 1)).  The quaternions are global quaternions.  The plane normal (vector) N defines the upwards direction of the plane surface.  Angles that go opposite of the normal vector is negative, whereas in the direction is positive.  With that in mind, the quaternion's angle cannot be greater than MAX degrees and less than MIN degrees.  These bounds are visualized by the cones (MIN is -90˚ in the diagram, so the cone is infinitely thin).

Thoughts:
My thought is that this algorithm would have to work in regards to the quaternions delta (unless the quaternion is in the MIN/MAX zones, which I will talk about later).  If the change (delta) of the quaternion results in the quaternion entering, or passing, the bounds, the change is capped (clamped) so the final quaternion never has a resulting angle that dissatisfy the bounds.
Clamping the delta could be achieved by determining the beginning and end angles, and obtaining a ratio to be used as the t value (the interpolator) of a Slerp function, so the final quaternion's angle is that of the bound.  The issue I see with this is how the roll would be manipulated due to the Slerp.  Would the intended, final roll of the quaternion be lost due to this Slerping?
This idea of change seems more important in the example of if the quaternion was to go from -89˚ to -91˚.  The final quaternion should be snapped back to -90˚ (if the bound was -90), instead of considering the new quaternion as -89˚ but from the other side.  Without this proper interpretation of the quaternion's angle, the quaternion could rotate around constantly and consistently due to the angle never being considered less than -90˚ and greater than 90˚.
Edge Case:
If the quaternion was to start inside the MIN/MAX zones (the cones), the quaternion would not have a change to define as the direction that the quaternion needs to move to get back to legal territory/angles (see angle a3 in diagram).  My thoughts is that a fallback plane normal that is orthogonal to plane normal N would have to be used, so the quaternion has a plane to rotate around.
Use Case:
Orbiting camera with user or author definable pitch angle clamping, and a varying change in "up".  Example of varying change of "up": Mario Kart 8 Deluxe.


texts: Texture Mapping to procedurally generated geometry

texts:
How can I calculate texture coordinates of such geometry?

The angle shown in the image (89.90 degree) may vary, therefore the geometry figure is changing and is not always such uniform.(maybe like geometry in the bottom of image) and red dots are generated procedurally depends on degree of smoothness given.


texts: Random layout rooms with intersecting walls

texts:
I am trying to layout few rectangle rooms on un unlimited map. The main condition is that every next room has to intersect with one of already placed with at least one point of the wall.

The number, width and height are random values generated by something like D&D dice rolling. Every next room can be adjacent to any placed rooms.
Result should look like a kind of dungeon (hope the picture makes it more clear)

I am afraid that different packing algorithms too heavy for that problem. I would greatly appreciate any advice!


texts: I am making a 2D Java game with Java's own drawing library. I was wondering how I would make a tile map display on the screen. I would prefer to use a GUI application to make the maps. I'm looking for orthogonal projection: a top down view.


texts: Could someone help me understand this game loop logic?

texts:
I'm learning Java game development and trying to dissect this game loop:

// Game loop
    final int TICKS_PER_SECOND = 60;
    final int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    final int MAX_FRAMESKIP = 5;

    long nextGameTick = System.currentTimeMillis();
    int loops;
    float interpolation;

    boolean running = true;
    while(running) {
        loops = 0;

        while(System.currentTimeMillis() > nextGameTick && loops < MAX_FRAMESKIP) {
            System.out.println(System.currentTimeMillis() + " > " + nextGameTick);
            update();
            ticks++;

            nextGameTick += SKIP_TICKS;
            loops++;
        }

        interpolation = (float) (System.currentTimeMillis() + SKIP_TICKS - nextGameTick)
                        / (float) SKIP_TICKS;
        render(interpolation);

        if(System.currentTimeMillis() - timeAtLastFPSCheck >= 1000) {
            System.out.println("FPS: " + ticks);
            gameWindow.setTitle(gameName + " - FPS: " + ticks);
            ticks = 0;
            timeAtLastFPSCheck = System.currentTimeMillis();
        }
    }

So far, here's what I understand:

TICKS_PER_SECOND is the amount of times we want the game to update per second
SKIP_TICKS is the max time that a game tick should take if we want to keep to our TICKS_PER_SECOND value
MAX_FRAMESKIP is the max amount of updates per render

Here's where I'm confused: the 'nextGameTick' variable takes the current time and then we go into the loop. The first logic that we come across is that while the current time is GREATER THAN 'nextGameTick' AND the loops of this logic is LESS THAN the MAX_FRAMESKIP (the max updates per render). I cannot get my head around why we are comparing if the current time is greater than the 'nextGameTick' - as far as I can see from the code the 'nextGameTick' is basically the time value if the update took the maximum amount of time allowed. But surely then we should be comparing if the current time is LESS THAN the maximum time allowed for the update - i.e. if the update is taking too long we break from the loop immediately and go to render. However if I change the GREATER THAN to a LESS THAN then update is never called.

I think what this logic is trying to do/doing (but I don't know how) is basically allowing the game to update more times than it renders - because a lot of people's computers will be fast enough to do so. So it allows us to update 5 times per render (while loops < MAX_FRAMESKIP). HOWEVER we also have the comparison to check if these updates are taking longer than expected in which case we should stop being greedy with the updates and go ahead and render (at least, this is what I think it's trying to do, please correct me if I'm wrong). But surely the current time being LESS THAN the time expected to take is the condition on which we want to continue updating?

As for the next part of the logic, the interpolation, I know we receive a value that we can use within rendering logic to draw game objects "in-between" updates so the movement doesn't seem jerky. Could someone expand on this though? And possibly even break down the actual code and how it arrives at the value we get.

So, to clarify, my overall question about this is:
 - Why do we check if the current time is greater than the time it was expected to take (this would surely mean it took longer than expected?? which is a BAD thing)
 - How does the interpolation value work, and how to we obtain it?

Thanks to anyone who can help me. Please just ask if you need more information from me.


texts: Applying Rotation Vector to OpenGL camera or "view matrix"

texts:
I'm building an augmented reality application where I want objects on the screen to move with respect to the orientation of the phone. For example, if the phone is held still - the object stays at the center of the screen. If the phone is rotated left about its vertical axis in portrait mode, the object moves to the right. This is the sensor I'm accessing in Android

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
        SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
        mGLAssetSurfaceView.getRenderer().setRotationMatrix(mRotationMatrix);
    }
}

This is how I'm applying it to my OpenGL renderer:

@Override
public void onDrawFrame(GL10 gl) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

    Matrix.multiplyMM(mViewMatrix, 0, mViewMatrix, 0, mRotationMatrix, 0);

    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);

    // Draw shape
    mSquare.draw(mMVPMatrix);
}

As you can see, I'm computing the product

MVRP

and passing that into my vertex shader. The result of this is the square in the middle of the screen rotating about its own axis, not with respect to the phone.


texts: How can I instantiate in the current rotation in Unity 2d?

texts:
Backstory

I'm currently working on a 2D sidescroller/platform game as a hobby, and I just started recently. Followed a few tutorials and such I managed to wrote my own code for basic command like walk, jump, health and so on. However my basic code wasnt perforning as I would expect, I needed a more "Tight" feeling with the movements so I followed a suggestion to use a physics based controller (Prime31's PC2D, Acrocatic or even Corgi Engine...)

Well, now the movements are what I feel is good, So I kind of dived in the scripts to add/remove/customize some code.

Question

I'm stuck now on a simple issue, I added these lines

public Transform weaponMuzzle;
public GameObject projectile;
float fireRate = 0.5f;
float nextFire = 0;

then in my Update()

if (Input.GetButtonDown("Fire2"))
{
  animator.Play.Weapon();
  fireProjectile ();
}

and here is the problem I have

void fireProjectile ()
{
  if (Time.time > nextFire)
  {
    nextFire = Time.time + fireRate;

    if (_motor.facingLeft)
    {
      Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0,0,180f)));
    }
    else if (!_motor.facingLeft)
    {
      Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
    }
  }
}

The prefabs are also physics based and they are fired with no problems, however they don't want to follow the current rotation of the player, they always go in the right X axis.

First of all, the facingLeft on my code is what I understand is the reference to the character controller motor, I tried with _motor.normalizedXMovement > 0 and _motor.normalizedXMovement < 0 (normalizedXMovement -1 is full left and 1 is full right) this just make it that you can only fire while moving, not stopped and the problem still persists.

I also tried with Quaternion.Identity instead of Euler and it's the same.

For a full source code : https://github.com/prime31/CharacterController2D

I'm kinda lost and it would means a lot if you can help me out on this issue.

Ps: I already searched here and other related forums but cannot find the answer, this is not a repost.


texts: Rotating a group of sprites - How to calculate origin

texts:
I am rotating a group of sprites in XNA, which I developed with the help of the following example:  http://msdn.microsoft.com/en-us/library/bb194912%28v=xnagamestudio.10%29.aspx

It all works very well, however, the rotations rely on a point of origin, which it will rotate around.  The problem is that I do not know how to calculate the point of origin, so that it is exactly in the center of the sprite group.

I am able to set the point of origin to where I want it, but as soon as the sprite group changes, the origin is typically off, and it doesn't rotate from the center of the group.

My main question, is there a way to calculate the center of a group of sprites?  My original idea was to calc the boundaries (left, right, top, bottom), and place the origin the the center, but this doesn't work properly.


texts: How to randomly place rectangle inside a larger bounding rectangle without intersecting other rectangles inside

texts:
Let us consider the case: there is an overall bounding rectangle (call this Rb) which contains a number of rectangles within it (call this set SRo). Now I would like to randomly position a new rectangle with known bounds (call this Rn) within the bounds of Rb without intersecting any of the rectangles in the set SRo

My current approach is rather brute force:

Generate random x-y coordinates for new rectangle
Check Rb contains Rn if it is placed at intended coordinates
Check Rn does not intersect any of rectangles inside set SRo

Anyone got any better idea?


texts: Splitting a texture atlas into seperate images

texts:
Possible Duplicate:
  How to decompose sprite sheet

I'm doing a port of an existing game and the designer no longer has all of the original art; he only has the resulting texture atlases he used when developing for iPad.  The tool I'm using won't support these files so I need to break them back out into separate PNG files.

I'm hoping someone knows of a software tool that does this.  PC software would be preferred in this case, but Mac would suffice.

Edit

To add some clarification; these texture atlases are in a simple gridded layout with even distribution and not packed.  No need to tie back to descriptor files; I just need a simple animation splitter type of tool where I can tell it the size of a frame, point it to the image and from that get a set of separate images.


texts: Why Won't Image Drawing Work In JavaScript

texts:
In my game at the beginning the first thing that you'll see is a campfire with this code:

 var campfire = new Image();
   campfire.onload = function () {
      ctx.drawImage(campfire, campfireX, campfireY);
 };
 campfire.src = "Sprites/Campfire.png";

However, it doesn't work, I put an

alert("All systems a-ok");

at the end and i get the alert so i don't understand why it's there. You can find the actual image file here   and the full code here. Sorry if I didn't format this well or something, I'm not very good at this =3

This may seem similar to an older question of mine in which I stated how to add a sprite onto the canvas, though in this case, I'm asking why the image doesn't appear on the canvas at all, even though there's no errors.


texts: How do I tile a specific region of a sprite?

texts:
I have a sprite that I use as a sprite sheet, where regions of the image represent various UI elements (window corner, border, background, etc.).

I want to use a certain region of that sprite as a texture that I can tile over a larger destination rectangle.

Setting the SamplerState to LinearWrap and then calling SpriteBatch.Draw with destination rect and source rect ends up stretching that region of the image, not tiling it.

All the examples I've seen that implement tiling use the entire sprite - I only want to use a region of it, and tile that region.

Is there any way to do this?

Edit for clarity:

Here's an example spritesheet

where I want that colored region. I have a rectangle that represents a window border, that is larger than the region in the source image.

Here's what I want to end up with

Here's the code I've been using.

spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);
spriteBatch.Draw(sourceTexture, windowTopBorderRect, sourceTextureRegionRect, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);

And what I get is the image stretched across the window border rectangle, instead of tiling the source region within that rectangle.


texts: How can I load/import GIS file (ESRI Shapefile) to Unity3D at runtime?

texts:
I'm new to Unity3D and I need to implement an open source Markerless Augmented Reality GIS mobile app (Android, IOS) to show the underground utilities (like wastewater pipes, water pipes, electricity lines,...) when the user moves with the mobile camera.

I found some SDKs for Unity3d that use location based AR (like Wikitude, Vuforia, ARCore, ... ) but I have not found a way to load a GIS file format (like ESRI Shapefile, CAD, GeoDB, ... ) at runtime and draw (points, lines, polygons) in 3D Unity shapes in its geographic location.

Screenshot from (vGIS) software to show what I need to implement
.


texts: Ensuring that saved data has not been edited in a game with both offline and online components

texts:
I'm in the pre-planning phase of coming up with a game design and I was wondering if there was a sensible way to stop people from editing saves in a game with offline and online components.

The offline component would allow the player to play through the game and the online component would allow them to play against other players, so I would need to make sure that people hadn't edited the source code/save files while offline to gain an advantage while online.

Game likely to be developed in either .Net or Java, both of which are unfortunately easy to decompile.


texts:
I have to calculate the intersection of a line segment (represented by 2 points) with a rectangle.

For example:

Axis aligned rectangle corners: (0, 0) (100, 100)

Point 1: (50, 50)

Point 2: (50, 150)

Expected result: (50, 100)

What would be the way to find the intersection of the line segment with the rectangle?


texts:
I am new to Unreal Engine with a very basic knowledge of working with the blueprints and code together. I am having trouble with making a reference of my Blueprint Game Mode in the code.

The question is that I have a Game Mode Blueprint (BP_GameMode) and I need to make a reference of it in a class Flag something like this:

BP_GameMode* TheGameMode = Cast<BP_GameMode>(GetWorld()->GetAuthGameMode());

Can anyone tell me how to do this?

Also, can I execute a custom event in my BP_GameMode like this?

TheGameMode->IncreamentScore(Amount);


texts: Is there a way to make the boundary between materials wavy?

texts:
I have a sea trading game that I'm working on developing. Right now, my world looks like this:

There are 4 different "biomes", with more to be added. Internally, this is a large mesh which has 4 different types of materials added to it, to make it work. Each region has a material associated with it.

The problem that I'm trying to overcome is to make it look less squary, I believe the process is known as bitmasking. The traditional way to do so I believe is to use images to show the boundary between each one, having one for each possible curve. That doesn't work with my current mesh architecture so far as I can tell. What I'm wondering is if there is a way to make the edges of the mesh to be curvy instead of straight lines. I assume it would have to be a shader of some kind, but my mind isn't quite figuring out the specifics of how to make it work. Any tips? Thanks!


texts: C++ Mouse picking for ray to plane intersection

texts:
I'm making a C++/OpenGL application (decidedly without GLM), and I'd like to understand how to create a ray from the camera eye to the mouse pointer, as well as detect an intersection point from the resulting ray onto a flat plane.

I have:
 - Camera position, camera pitch/yaw, camera's Fwd vector
 - mouse coordinates in pixel measurements (which I can convert to -1:+1 screen space)
 - A world system where XY are the horizontal and Z is up
 - A flat plane where Z=0
 - My own matrix class which is basically just a float[16] and accessed (Get()) as a float*
 - Basic matrix multiply function, cross, dot product functions.

I'm still trying to learn 3D math (this project is somewhat of a reason for that), so I'm still somewhat hazy on how to accomplish this.  Most tutorials I can find are Unity tutorials, or involve using an Unproject function from glu or GLM.

I'd hopefully like to understand how to accomplish this manually as I'd like to understand what's happening.  Thank you for any wisdom or guidance.


texts:
Copied from Computer Graphics SE.

I am implementing a post-processing effect in my DirectX 11 pet renderer. The post-processing pass is implemented by rendering a full-screen quad covered with texture containing original rendered image, which works as it should, but I have problems with downscaling the texture.

The non-processed testing scene looks like this (three very bright emmissive spheres):

I see no problem at this stage, but when I run the first post-processing pass, which just down-scales the image by the factor of 8 using the texture sampler, the result is very flickery (up-scaled for clarity):

I expected a mipmap would solve or at least reduce the flickering, but it didn't change a thing. What am I doing wrong?

RenderDoc Update

After investigating the issue using RenderDoc I found that the mipmap is being generated successfully and it's third level looks like this:

However, the output of the down-scaling pass looks like this:

As if the sampler didn't use the mipmap at all. Don't get distracted by coloured object instead almost white ones. I lowered the sphere brightness a bit while investigating the bug.

Even if I choose the mipmap level explicitly

float4 vColor = s0.SampleLevel(LinearSampler, Input.Tex, 3);

it changes nothing :-/

RenderDoc also says "LOD Clamp 0-0" for the used sampler. What is it? Couldn't this be the problem?

DirectX details

Samplers

D3D11_SAMPLER_DESC descSampler;
ZeroMemory(&descSampler, sizeof(descSampler));
descSampler.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
descSampler.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
descSampler.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;

descSampler.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
mDevice->CreateSamplerState(&descSampler, &mSamplerStateLinear);

descSampler.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
hr = mDevice->CreateSamplerState(&descSampler, &mSamplerStatePoint);

...are set right before rendering the screen quad

ID3D11SamplerState* aSamplers[] = { mSamplerStatePoint, mSamplerStateLinear };
mImmediateContext->PSSetSamplers(0, 2, aSamplers);

...and used within the down-scaling PS shader

SamplerState PointSampler  : register (s0);
SamplerState LinearSampler : register (s1);

Texture2D s0 : register(t0);

float4 Pass1PS(QUAD_VS_OUTPUT Input) : SV_TARGET
{
    return s0.Sample(LinearSampler, Input.Tex);
}

Texture

D3D11_TEXTURE2D_DESC descTex;
ZeroMemory(&descTex, sizeof(D3D11_TEXTURE2D_DESC));
descTex.ArraySize = 1;
descTex.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
descTex.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
descTex.Usage = D3D11_USAGE_DEFAULT;
descTex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
descTex.Width  = width;
descTex.Height = height;
descTex.MipLevels = 0;
descTex.SampleDesc.Count = 1;
device->CreateTexture2D(&descTex, nullptr, &tex);

...it's render target view

D3D11_RENDER_TARGET_VIEW_DESC descRTV;
descRTV.Format = descTex.Format;
descRTV.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
descRTV.Texture2D.MipSlice = 0;
device->CreateRenderTargetView(tex, &descRTV, &rtv);

...it's shader resource view

D3D11_SHADER_RESOURCE_VIEW_DESC descSRV;
ZeroMemory(&descSRV, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC));
descSRV.Format = descTex.Format;
descSRV.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
descSRV.Texture2D.MipLevels = (UINT)-1;
descSRV.Texture2D.MostDetailedMip = 0;
device->CreateShaderResourceView(tex, &descSRV, &srv);

Explicit generation of mipmap is called after the scene was rendered into the texture and another texture was set as a render target.

ID3D11RenderTargetView* aRTViews[1] = { mPass1Buff.GetRTV() };
mImmediateContext->OMSetRenderTargets(1, aRTViews, nullptr);

mImmediateContext->GenerateMips(mPass0Buff.GetSRV());

ID3D11ShaderResourceView* aSRViews[1] = { mPass0Buff.GetSRV() };
mImmediateContext->PSSetShaderResources(0, 1, aSRViews);

The code is compiled in debug and the D3D device was created with D3D11_CREATE_DEVICE_DEBUG flag and I get no runtime errors on the console.


texts: This is a very short question. I want to implement ambient light in the color of daylight from the sun. What is the color value of sun light?


texts: How can I create this navigation system?

texts:
I try to make a navigation/waypoint system. Well I have a concept but no idea how I could create this system. Well here's an image and an explanation:

You can see 3 waypoints as well as an goal and a player. The function should take the player position (X,Y,Z), a waypoint position array as well as an goal position. If the player is now on the position like in the image then it should output the second waypoint position because it's the closest waypoint in the direction of the goal. If the player is on the second waypoint position then it needs to output the third waypoint and so on  to the finish. Well that's my crude concept. I hope that somebody can help! Thanks in advance :D

NOTE: You can add any values you want to add the most important thing is that it helps me :)


texts:
I have been working with Tiled and Cocos2d lately but am having problems understanding how Im suppose to be doing the maps.
Tiled is not an image editor, so I create my tileset in Gimp.  However it seems impossible for me to get grid lines that are the same as Tiled and so I dont know prior to importing the image (into Tiled) where the grid lines will be.

See the image below.  Both Tiled and Gimp's grid lines are set to 32px however the grid lines are nothing alike between the two programs

How can I get the grid lines to match so that I can draw stuff knowing how many tiles it will take.  Is there a better program for creating tileset or another way to do it?


texts: In Unity, Is it possible to get gameobjects from non-open Scene?

texts:
Sorry for my english mistakes,I treid my best to make myself easy to be understood.

On Unity 2017.1 + C#.

I am trying to make UnitTest to check the potential errors in the scenes.
and when I want to get the gameObjects from the two deifferent scenes,
I can only get the scene which is open currently in the editor.

How to solve this problem?
Or This is impossible to be done in Unity mechanism?

Two Secens I have:

Scene1 hierarchy:

Scene2 hierarchy:

Code:

Result: Only get the open scene's infomation

My Final Solution

Thanks for the help, you guys help me make progress.

This is the feedback of my work.
When I tried to solve my problems with the instruction,
I ran into some obstacle.

So, I followed the suggestion of the error message.

And the result is pleasant.

The possible reason I can not get the same result at the begining,
It may be because the different test mode(playMode/EditMode)

I will let myself take a break now and not dig deeper at this moment.

Thanks for your help and wish my dicovery can help someone too.


texts: Where should I put the code for objects interactions?

texts:
I'm working on a 2D puzzle game, and one of the features is the ability to push crates so you can climb on top of them to get to a destination.

I've tried many things to get this to work but none of them succeed.

My main problem is that I don't know where to put my code. For example, I don't want to handle the movement of the crate in the player class because that wouldn't be neat, the same way some people say something along the lines of "If you're making chess, the rules of the pawn and knight shouldn't be in the rules of the queen".

If anyone has an answer or could provide a pseudo-code explanation it would be appreciated.


texts: Detected problems - libandengine.so text relocations

texts:
I am creating a game with AndEngine on Android Studio (v.3.0.1). When I run the game on my Honor 8 (7.0) everything works as expected. But on the Samsung A3 (7.0) or J5 (7.1.1) a Dialog appears saying: 'Detected problems with app native libraries (please consult log for detail): libandengine.so: text relocations.

Logcat: W/linker: /data/app/whatever.at.hatchy-1/lib/arm/libandengine.so has text relocations. This is wasting memory and prevents security hardening. Please fix.

AndEngine build.gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 21
    buildToolsVersion "26.0.2"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 21

        ndk {
            moduleName "andengine_shared"
        }
    }
    sourceSets {
        main {
            jni.srcDirs = []
        }
    }
    compileOptions {
        encoding "UTF-8"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

App build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "whatever.at.app"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile project(':andEngine4')
    compile 'com.google.android.gms:play-services-analytics:11.8.0'
    compile 'com.google.android.gms:play-services-ads:11.8.0'
    //compile 'com.android.support:support-v4:23.4.0'
}

Additionally the camera/gameview size changes and doesn't adapt to the set width and height but don't know if this problem is dependent on the same issue.

Does anybody know what todo in such case?

Thanks


texts: Monogame problem with flat shading low poly terrain

texts:
I have been dabbling in 3d rendering recently and I am having a problem with the shading on the mesh I am using.

The code I am using to calculate the normals for all the triangles is as follows.

for (int i = 0; i < Indices.Length; i += 3)
{
    Vector3 p1 = Vertices[Indices[i]].Position;
    Vector3 p2 = Vertices[Indices[i + 1]].Position;
    Vector3 p3 = Vertices[Indices[i + 2]].Position;

    Vector3 v1 = p2 - p1;
    Vector3 v2 = p3 - p1;
    Vector3 normal = Vector3.Cross(v1, v2);

    normal.Normalize();

    Vertices[Indices[i]].Normal = normal;
    Vertices[Indices[i + 1]].Normal = normal;
    Vertices[Indices[i + 2]].Normal = normal;
}

None of the triangles in the mesh share vertices so that I can achieve a low polygon look. When it render's half the faces are dark and the other half look like they are correctly shaded. Does anyone have any idea what is going on here and what I may be doing incorrectly?


texts:
I'm trying to make a dungeon crawler but I need to make the monster move around each turn.

Here's what I tried:

My map is initialized like this:

char map[10][10];

and this is how I spawn the monsters to avoid overwriting:

void fieldinfo::RandomizeMonsterPositions()
{
    int Mcounter=0;
    amountEnemies=10;
    int i=0;
    srand(time(0));

    do
    {
        MposX=rand()%9;
        MposY=rand()%9;

        if(map[MposX][MposY]==enemy)
        {
            //do nothing
        }
        else if(map[MposX][MposY]==player)
        {
            //do nothing
        }
        else
        {
            map[MposX][MposY] = enemy;
            tempPosX[i]=MposX;
            tempPosY[i]=MposY;
            i++;
            Mcounter++;
        }

    }while(Mcounter<10);
}

You can see that I tried to "save" each monster's position in the tempPosX/Y variables to use them here, in my movement logic:

void fieldinfo::RandomizeMonsterMovement()
{
    int mouvement;
    for(int i; i<amountEnemies; i++)
    {
        mouvement=rand()%0;
        switch(mouvement)
        {
        case 0:
            tempPosX[i]++;
            MposX=tempPosX[i];
            break;
        case 1:
            tempPosX[i]--;
            MposX=tempPosX[i];
            break;
        case 2:
            tempPosY[i]++;
            MposY=tempPosY[i];
            break;
        case 3:
            tempPosY[i]--;
            MposY=tempPosY[i];
            break;
        }
    }
}

This doesn't work and I don't know why?


texts:
Currently, my LibGDX game consists of a 512 x 512 map of Tiles and entities such as players and monsters. I am wondering how to efficiently save and load the data of my levels. At the moment I am using JSON serialization for each class I want to save. I implement the Json.Serializable interface for all of these classes and write only the variables that are necessary.

So my map consists of 512 x 512 tiles, that's 260,000 tiles. Each tile on the map consists of a Tile object, which points to some final Tile object like a GRASS_TILE or a STONE_TILE. When I serialize each level tile, the final Tile that it points to is re-serialized over and over again, so if I have 100 Tiles all pointing to GRASS_TILE, the data of GRASS_TILE is written 100 times over. When I go to load/deserialize my objects, 100 GrassTile objects are created, but they are each their own object. They no longer point to the final tile object. I feel like this reading/writing files very slow.

If I were to abandon JSON serialization, to my knowledge my next best option would be saving the level data to a sql database. Unless there is a way to speed up serializing/deserializing 260,000 tiles I may have to do this. Is this a good idea? Could I really write that many tiles to the database efficiently?

To sum all this up, I am trying to save my levels using JSON serialization, but it is VERY slow. What other options do I have for saving the data of so many tiles.

I also must note that the JSON serialization is not slow on a PC, it is only VERY slow on a mobile device. Since file writing/reading is so slow on mobile devices, what can I do?


texts: How is animation handled in non-immediate OpenGL?

texts:
I'm a newbie to modern OpenGL. I'm comfortable with the immediate OpenGL methodology, but I've never done any serious use of VBOs. My question is about animation. In immediate mode, to achieve animation you just have to stream different vertex positions (interpolated from keyframes) in object space.

How is this achieved in non-immediate OpenGL? Obviously, uploading fresh VBO data for each frame is sure going to hog the graphics bus. I haven't found any literature about the modern way to do it. Thinking about it, I came to several options:

Attributes: animation as a 3d offset. For each frame, a different (possible interpolated) offset attribute is passed for each vertex, applied to the same vertex each keyframe.
Indices: storing keyframes as absolute vertices and accesing them through indexing, using a different set of vertices for every keyframe. I find this approach impossible, since you can't access adjacent keyframes and therefore can't interpolate between them. Also, seems like a bad idea for procedural animation.
Texture: this might be very stretchy but sounds like a good solution for me. Again, animation is thought as an xyz offset for each vertex. Each keyframe can be stored in a 1D texture where the dimension maps to vertexID.If I'm not mistaken, in OpenGL 4.0 you can access textures from any shader, so you could read this texture from the vertex shader and apply each vertex transformation.  A 2D texture could hold several frames. You still perform interpolation (and if interpolation works for textures outside of fragment shader, which I'm not sure of, you can linearly interpolate for free!) This could be applied to more complex animation systems like bone animation without much effort.

Am I overthinking this? Can anyone shed some light?


texts: In Unity, is there a difference between Vector3.down and -Vector3.up?

texts:
I've noticed numerous tutorials and examples using something like "transform.up * -1" or "-Vector3.up" instead of simply saying "transform.down" and "Vector3.down".

Is there a good reason for this, or is it simply a style difference?

I'm specifically thinking about downward raycasts, if that matters at all.


texts: Quill18 Tutorial broken or Have I broken something?

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

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

I have attached the code below

public class Turret : MonoBehaviour {

public Transform turretTransform;

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

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

        Quaternion lookrot = Quaternion.LookRotation(dir);

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

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


texts: Adding Grass to a Low-Poly Mesh in Unity

texts:
How would I go about adding grass to a low-poly mesh in Unity?

Here is what I have looked into:

Object2Terrain: I am not using Unity's built in terrain system because I am going for a low-poly art style. I tried converting my terrain mesh object to a terrain (using Object2Terrain) however this removes the sharp edges on the terrain, because Unity uses a height map for optimization.
PolyMesh: From the get-go I knew this approach wasn't going to work. I knew it would be incredibly inefficient to render that many meshes at once. I still tried it though, and to no surprise, it was very laggy.
Particle System: From what I've read, this should work fine for randomly scattering grass over your mesh, however I do want some control when placing grass. I followed this tutorial image as suggested by a comment in this question on Reddit, however, I was never able to achieve the desired result. Nevertheless, I do want control over placing the grass, and so I moved onto another approach.
Shaders: I'm not experienced at all when it comes to creating (or even using) shaders, and it's quite a daunting topic to me. I've read that this is the most efficient approach, however haven't been able to understand how this means I could draw grass onto a mesh? On the same Reddit post linked above, "UpstairsCurrency" was kind enough to link their source code (here), however I'd like to understand what is happening? I'm reluctant to say that I'm not even sure I understand how to implement it into my project in the first place. Would appreciate any sources for reading up to help understand what is going on!

Thanks!


texts:
I want to make game level select screen.

There are some stages which open, and some that are not.

So if you clear a second stage and quit the game for a while, when you come back, you can start at stage 3, 2 or 1 whatever you can click, but not from stage 4; you can't play it without completing stage 3.

I want to make something like this, but I have no idea how. What should I use to do it (boolean, database...)?

Can you give me some simple code structure?


texts: Circle physics and collision using vectors

texts:
This is a problem I've been having, When making a set number of filled circles at random locations on a JPanel and applying a gravity (a negative change in the y), each of the circles collide. I want them to have collision detection and push in the opposite direction using vectors but I don't know how to apply that to my scenario could someone help?

public void drawballs(Graphics g){
    g.setColor (Color.white);

    //displays circles
    for(int i = 0; i<xlocationofcircles.length-1; i++){
    g.fillOval( (int) xlocationofcircles[i],  (int) (ylocationofcircles[i]) ,16 ,16 );
    ylocationofcircles[i]+=.2; //gravity
    if(ylocationofcircles[i] > 550) //stops gravity at bottom of screen
    ylocationofcircles[i]-=.2;

    //Check distance between circles(i think..)
    float distance =(xlocationofcircles[i+1]-xlocationofcircles[i]) + (ylocationofcircles[i+1]-xlocationofcircles[i]);

    if( Math.sqrt(distance) <16)
    ...


texts:
I'm new to the tilemap feature of Unity, and I'm having a hard time with all those coords.

I created a new project, added an isometric tilemap and left all values to their default. In the Unity Editor (and in-game at runtime as well), the coordinates of the cells are like this:

This is pretty disturbing to me and it will be to most players (not programmers) too I guess.

I would like something like this:

However, I can't figure out how to do the transformation.

I tried this:

Vector3 currentWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int currentCellPos = _grid.WorldToCell(currentWorldPos); // This gives the coordinates as in the Unity Editor except for z
currentCellPos.z = 0; // Set z to 0 so the coordinates of the cell are exactly as in the Unity Editor
Vector3 cartesianCellPos = new Vector3((2 * currentCellPos.y + currentCellPos.x) / 2, (2 * currentCellPos.y - currentCellPos.x) / 2, 0); // Try to transform the Unity coordinates into cartesian coordinates: WRONG RESULT

But this calculation gives weird results, not what I expect at all.

Do you know how I could transform the Unity coordinates shown in the first screenshot into the coordinates shown in the second screenshot?


texts:
Well, my question in rather simple - or so I hope. What I would like to do is separate my game assets in the Unity game engine into separate files for the build. This way not all the assets are in one large file, therefore making for easier and faster updates (don't have to re-download one large file if there's only a small change to one asset). How would I go about doing this? The best case solution would be if I could have everything separated during the final build, this way if I update one tree asset I don't need to update all tree assets, but I'm not sure if this is possible.

Example Structure:
+ A common set of assets that's loaded on startup (menu textures, trees used often, etc).
+ A set containing trees, rocks, and other foliage.
+ A set containing various scripts (AI scripts that would get updated frequently for example).

Thanks for the help!


texts: What is the size limit to the Unity 2017.2 Tilemap?

texts:
I've been digging through the documentation on the Tilemap feature of Unity 2017.2.

Does Unity limit the maximum number of tiles it will support for a particular tilemap mesh?

I know that each tile is instantiated once and used to texture the quads on the Tilemap mesh at runtime, so I would guess that the mesh quad count limit is ultimately dependent on the hardware, and more or less is arbitrarily high.

Is that a correct assumption, or is there a hard cap in the engine?


texts: Make my Character face the same way as my Camera as I rotate the camera

texts: Before posting, I've already tried parenting the camera to the Character mesh head and setting controller yaw, that didn't work, in fact it invalidated my blueprint to set my Mouse X and Y for the pitch and yaw that allowed me to move my camera in the first place. So I need a different method to make my character follow the way my camera is facing whenever I rotate, otherwise when I turn around I just face my Character.


texts: In Box2D, how can I check for bodies within a circle?

texts:
I'm trying to sample random positions to find one that is sufficiently far from other bodies.

Hence I'd need to test for bodies within a given circle. So far, I've used b2World::QueryAABB around my circle (which does what I want but for a rectangular area), then manually doing an intersection test with all the fixtures it gives me.

It seems to me like Box2D should already provide such functionality—is there a way that lets me do this without reinventing most of the wheel?


texts: How to read ARGB pixel data from SDL2 surface and store them in an array?

texts:
I've been trying for hours now to figure out why this piece of code is giving me seg fault, but can't figure out why.
 void pixel::Texture::LoadTexture(const char* filepath)
 {
    SDL_Surface* image = IMG_Load(filepath);
    SDL_Surface* formattedImage = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_ARGB8888, 0);

    textureBuffer = new Uint32[formattedImage->pitch * formattedImage->h];

    width = formattedImage->w;
    height = formattedImage->h;
    pitch = formattedImage->pitch;

    SDL_LockSurface(formattedImage);

    Uint32* pixels = (Uint32*)formattedImage->pixels;

    int bpp = formattedImage->format->BytesPerPixel;

    for(int y = 0; y < height; y++)
        for(int x = 0; x < width; x++)
            textureBuffer[(formattedImage->pitch * y) + (x * bpp)] = pixels[(formattedImage->pitch * y) + (x * bpp)];

    SDL_UnlockSurface(formattedImage);

    SDL_FreeSurface(image);
    SDL_FreeSurface(formattedImage);
 }

Essentially, what I'm doing is I have an array of unsigned 32 bit integers called the texture buffer. All I do is load an image into a surface then convert it's pixel format to ARGB then start reading each pixel and storing it inside my texture buffer array but for some reason the pixels array gets an out of bounds error at some point in runtime and I can't figure out exactly why.


texts: How to use AssetBundles with Unity WebGL

texts:
I have a Unity WebGL project that tries to load AssetBundles, but I get an error:

  Unable to open archive file: http://localhost:50212/StreamingAssets/Bundles/language_english

The code that creates the AssetBundles:

using UnityEditor;
using System.IO;
using UnityEngine;

public class JC_Bundler: Editor
{
    [MenuItem("Assets/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        string path = Path.Combine(Application.streamingAssetsPath, JC_Bundles.Directory);
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
        AssetDatabase.Refresh();
    }
}

I can see the AssetBundles do get created and it works on other Windows Standalone and Android platforms.

The code that read the AssetBundle:

public void PrepareLanguageAssets(SystemLanguage language, UnityAction onDone, UnityAction onFail)
{
    StartCoroutine(LoadBundle("language_" + language, bundle => {
        if (bundle == null)
        {
            onFail();
        }
        else
        {
            if (languageBundle) languageBundle.Unload(true);
            languageBundle = bundle;
            onDone();
        }
    }));
}

public void LoadLanguageAsset<T>(String name, UnityAction<T> callback) where T : UnityEngine.Object
{
    StartCoroutine(LoadAsset(languageBundle, name, callback));
}

IEnumerator LoadAsset<T>(AssetBundle bundle, string objectNameToLoad, UnityAction<T> callback) where T: UnityEngine.Object
{
    AssetBundleRequest asset = bundle.LoadAssetAsync<T>(objectNameToLoad);
    yield return asset;

    callback(asset.asset as T);
}

So when I switch my Unity Editor Platform to WebGL and do a "Build And Run" with the same project I see the above mentioned error.

How can I load AssetBundles in WebGL?


texts: How to code shaders in C# without resorting to other programming languages?

texts:
I'm working on game and game engine and want a way to prototype shaders. I'm not skilled with C++ or GLSL or HLSL or STH, but I can code in C#.

My question is: How can I code shaders in C#, without using the other mentioned languages?


texts: OpenGL/C++ Rotate relative to shooting gun

texts:
I'm trying to make a 2D game where I have a gun that i use to shot things in the direction of the mouse resulting in an angle that I can get. I have some problems with the trajectory of the bullet because I don't know what to put in the Transpose and Rotate function.
For example Point 1 has x = 20 and y  = 30. I want to shot in the direction of Point 2  at x = 50 and y = 50. To do that i get an angle 't' which I use in the rotate function. But the reality is that I get the animation that I presented in the photo. I increase the x coord of the bullet because I can only shot in right side so only positive x. The bullet is moving on the 0x axis rotated at an angle t but at the same y as the gun.

What I want is something like

I'm sorry if this is a duplicate I couldn't find a solution to my problem. I think the resulting Matrix should have the form : Translate * Rotate * Translate but I can't find the right x and y.
Sorry if this seemed dumb and thank you for your time!


texts: How can I make my sprite jump up and move forward at the same time?

texts:
I'm trying to make a sprite's movements work. For some reason, he can only jump and then move, or move and then jump, but never at the same time.  I'm using InputProcessor and a TiledMap system.  Here's some code :

@Override
public boolean keyDown(int keycode) {
    switch(keycode) {
    case Keys.W:
        if(canJump) {
        velocity.y = speed;
        canJump = false;
        }
        break;
    case Keys.A:
        velocity.x = -speed;
        break;
    case Keys.D:
        velocity.x = speed;
        break;
    }
    return true;
}

@Override
public boolean keyUp(int keycode) {
    switch(keycode) {
    case Keys.W:
        velocity.y = 0;
        break;
    case Keys.A:
        velocity.x = 0;
        break;
    case Keys.D:
        velocity.x = 0;
        break;
    }
    return true;
}


texts: What are good puzzle game interface design principles?

texts:
I'm building a prototype puzzle game at the moment. I'm just curious as to the principles behind building graphic interfaces within games.
At the minute I'm looking at designing the graphics for an interface in something like Illustrator. I'm looking at one graphic (650 x 650 px) that incorporates the play area (400 x 550 px) as a blank square, with a nice border on the right hand side (vertically down the screen) and a border along the bottom too. I'm leaving a "blank" rectangle on the vertical border to incorporate a timer into it, and three "blank" squares along the bottom to incorporate icons to represent lives or power-ups or something, which I'll design later and animate later.
Is this an acceptable/sensible approach?


texts: Splitting logic into threads in Java tower defence game

texts:
I'm making a tower defence game in Java!
It's my first game development.
I want to know how many threads Do I need to create in a game, to split logic..
I've made this one:

Main App thread  (adds component thread - add(screen))

1.1.1 Thread (graphic updates)
1.1.2 Bullets physic
1.1.3 Mobs physic
1.1.4 Towers physic

Is it normal to split this logic?


texts: What happens if I increment a completed achievement on Google Play?

texts:
This question is about GPGS (Google Play Game Services). Say we have three achievements like:

Achievement A: Kill a total of 3 enemies
Achievement B: Kill a total of 6 enemies
Achievement C: Kill a total of 12 enemies

As they are all measured with total amount of kills, when players kill an enemy, all them three should increase. So what happens if I continue to send increments after total amount exceeds 3 for A, 6 for B, 12 for C?


texts: Approaches to partner trick taking card game AI

texts: I am creating an android game out of a partner based trick taking card game. What are some generic approaches to AI players for these types of games and what are the advantages/disadvantages of each?


texts:
I want to create a menu for an SDL game, so I load an Image to an SDL_Window as the background, then I try to load the next image which will be a button but it doesn't display the button to the window, it just displays the background.

I'm a newbie so perhaps it is an obvious mistake.

Here's what I got:

#include <stdio.h>
#define SDL_MAIN_HANDLED
#include "SDL.h"

int main(int argc, char *argv[])
{
    int a = 1;
    SDL_Event event;

    SDL_Window* window;
    SDL_Surface* background_surface;
    SDL_Texture* background_texture;
    SDL_Renderer* background_renderer;
    SDL_Surface* button_surface;
    SDL_Texture* button_texture;
    SDL_Renderer* button_renderer;

    SDL_Rect button_pos;
    button_pos.h = 65;
    button_pos.w = 320;
    button_pos.x = 0;
    button_pos.y = 0;

    SDL_Init(SDL_INIT_VIDEO);
    window = SDL_CreateWindow(
        "Cosmic Racing",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        320,
        568,
        SDL_WINDOW_OPENGL
    );
    background_renderer = SDL_CreateRenderer(window, -1, 0);
    background_surface = SDL_LoadBMP("Background.bmp");
    background_texture = SDL_CreateTextureFromSurface(background_renderer, background_surface);
    SDL_RenderCopy(background_renderer, background_texture, NULL, NULL);
    SDL_RenderPresent(background_renderer);

    button_renderer = SDL_CreateRenderer(window, -1, 0);
    button_surface = SDL_LoadBMP("Play.bmp");
    button_texture = SDL_CreateTextureFromSurface(button_renderer, button_surface);
    SDL_RenderCopy(button_renderer, button_texture, &button_pos, NULL);
    SDL_RenderPresent(button_renderer);

    while(a)
    {
        SDL_PollEvent(&event);
        if(event.type == SDL_QUIT)
        {
            a = 0;
        }
    }

    SDL_DestroyTexture(button_texture);
    SDL_FreeSurface(button_surface);
    SDL_DestroyRenderer(button_renderer);
    SDL_DestroyTexture(background_texture);
    SDL_FreeSurface(background_surface);
    SDL_DestroyRenderer(background_renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

BTW if you find additional mistakes please tell me. Thank you ;)


texts:
I have a gameobject with a SpriteRenderer, and I want it to cast (and receive) shadows like a 3D model. The sprite will turn around depending of his direction, so all faces must cast shadows.

I already activated Cast Shadows and Receive Shadows in the Sprite Renderer component, and also included a Transparent Cutout shader with the Cull Off instruction (so all faces are drawn), but only one side of the sprite is being affected by light, while the other is even darker. To ilustrate:

How can I achieve an sprite casting shadows with both faces?


texts: How to correctly export UV coordinates from Blender

texts:
Alright, so I'm just now getting around to texturing some assets. After much trial and error I feel I'm pretty good at UV unwrapping now and my work looks good in Blender.

However, either I'm using the UV data incorrectly (I really doubt it) or Blender doesn't seem to export the correct UV coordinates into the obj file because the texture is mapped differently in my game engine. And in Blender I've played with the texture panel and it's mapping options and have noticed it doesn't appear to affect the exported obj file's uv coordinates.

So I guess my question is, is there something I need to do prior to exporting in order to bake the correct UV coordinates into the obj file? Or something else that needs to be done to massage the texture coordinates for sampling. Or any thoughts at all of what could be going wrong?

(Also here is a screen shot of my diffused texture in blender and the game engine. As you can see in the image, I have the same problem with a simple test cube not getting correct uv's either)

Edit -

Added my geometry pass shader source code to show how I'm rendering and sampling the diffuse texture. I'm simply using the UV coordinates provided by the obj file and an anisotropic sampler.

Texture2D    diffuseTexture : register(t0);
SamplerState textureSampler : register(s0);

cbuffer ObjectTransformBuffer : register(b0) {
    float4x4 worldTransformMatrix,  // Translates to world space.
             cameraTransformMatrix; // Translates to camera space. (not including rotation)
};

cbuffer ScreenTransformBuffer : register(b1) {
    float4x4 viewProjectionMatrix; // Rotates to camera space and then projects to screen space.
}

cbuffer MaterialBuffer : register(b2) {
    float3 materialDiffuseAlbedo;
    float  materialSpecularExponent;
    float3 materialSpecularAlbedo;
    bool isTextured,
         isLighted;
};

struct vsInput {
    float3 positionLS : POSITION;
    float3 textureLS  : TEXTURE; // Input signature uses a uvw coordinate but w is 0 and not needed for any geo pass textures.
    float3 normalLS   : NORMAL;
};

struct vsOutput {
    float4 positionCS : SV_POSITION;
    float2 textureLS  : TEXTURE;
    float3 normalWS   : NORMAL;
    float3 positionWS : POSITION;
};

struct psOutput {
    float4 positionWS : SV_Target0;     // Surface positions.
    float4 normalWS   : SV_Target1;     // Surface normals.
    float4 diffuseAlbedo : SV_Target2;  // Surface diffuse albedo.
    float4 specularAlbedo : SV_Target3; // Surface specular albedo.
};

vsOutput VS( in const vsInput _in ) {
    vsOutput _out;

    _out.positionCS = mul(float4(_in.positionLS, 1.0f), mul(cameraTransformMatrix, viewProjectionMatrix));
    _out.positionWS = mul(float4(_in.positionLS, 1.0f), worldTransformMatrix).xyz;
    _out.normalWS   = mul(float4(_in.normalLS, 0.0f), worldTransformMatrix).xyz;
    _out.textureLS  = _in.textureLS.xy; // w coordinate is 0 and not needed.

    return _out;
}

psOutput PS( in vsOutput _in ) {
    psOutput _out;

    // Use the alpha channel to indicate specular light intensity.
    _out.normalWS = float4(normalize(_in.normalWS), materialSpecularExponent);

    float _lightEffectModifier;
    if (isLighted)
        _lightEffectModifier = 1.0f;
    else _lightEffectModifier = 0.0f;
    // Use the alpha channel to indicate whether the surface is affected by light for the light pass.
    _out.positionWS = float4(_in.positionWS, _lightEffectModifier);

    _out.diffuseAlbedo = float4(materialDiffuseAlbedo, 1.0f);
    if (isTextured)
        _out.diffuseAlbedo *= diffuseTexture.Sample(textureSampler, _in.textureLS.xy);

    _out.specularAlbedo = float4(materialSpecularAlbedo, 1.0f);

    return _out;
}


texts: Multi Resolution graphic for ios 4 and ios 5

texts:
I have used cocos2d-x to develop a game for iPhone 4, iPhone 4s, iPhone 5 with different screen sizes (3.5 inch and 4 inch)

First, my resource are designed for iPhone 4 and iPhone 4s with 3.5 inch screen size.

So if I want to use for iPhone 5 with 4 inch screen size. what should I do?


texts:
Is it possible to create VAO's while my computer doesn't support openGL 3.0 or higher? I managed to create a vertex buffer object and draw a rectangle.
But then I changed my lwjgl libraries to the latest version, and now I'm using GLFW for creating my display.

Thw problem is: when i create a rectangle using a simple VBO, it has no errors.
When I follow tutorials and start using a VAO, I get a function not available exception on glGenVertexArrays().
After searching on Google, a came to the conclusion that some devices do not support openGl 3.0 or higher. And I also tried a few configuration things, but I can't get to work with VAO's. Is there another way of using them in a lower version?


texts: Finding the monitors orientation in XNA for Windows

texts:
Just to be clear this is not for Windows Phone 7. =)

I've got some interesting requirements for a project and I'm having trouble trying to find the information I need.

I have two monitors. The default monitor is landscape. The second monitor is portrait.

Right now I save the width and height and then change Graphics.PreferredBackBufferWidth and Graphics.PreferredBackBufferHeight to the values returned from GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width (1920) and GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height (1080) right before toggling to full screen. This works fine on the monitor in landscape mode. The monitor in portrait however scales 1920x1080 to fit onto the 1080x1920 screen.

I'm looking for either a way to determine that the monitor is in portrait mode or have the CurrentDisplayMode.Width and CurrentDisplayMode.Height return the portrait appropriate values.

I've been rifling through the XNA Framework documentation and googling like mad and not finding anything helpful.


texts: What's the difference between a "Release" Xbox 360 build and a "Debug" one?

texts:
I've got a build of my game that works on Windows under a release and debug build as expected. When I deploy the debug version of the game to the Xbox, it works as expected and runs the same as on Windows - however when I deploy the release version to the XBOX I get different behaviour within the game.

I'm using a 3rd party library for the collisions (which is where I am seeing differences between the release and debug versions of my game); so I can't see what's actually different but I suspect they have some compiler directive for Debug on the Xbox to the Release version on the Xbox.

As such, I'm thinking that I may need to release my game with the Debug build instead of the Release build but I want to know what issues I can expect by doing so? Are there any significant performance issues between the two build profiles?


texts: What is a good book on physics for game development?

texts: I'm looking for a good beginners' book on the subject of physics in game development. Something that focuses on 2D games would be preferable.


texts:
I was looking for some inspration for my Voxel based game I am writting and came across this: http://www.youtube.com/watch?v=rL8zDgTlXso. I would like to know how to go about (or preferably source examples) of how I would do that, in real time, and infinitley. In addition to that I was wondering how I would do this with a voxel based terrain?

A procedural planet generator in 3D which constructs voxel data, my voxels are of the same size of thoose in minecraft.

Any ideas?

Edit:

I ported the simplex noise function i_grok suggested written in C++/Python to C#, I sure hope it works :)

http://pastebin.com/TZSQwnye

Edit 2:

float noise(float x, float y, float z, float persistance, float amplitude, float frequency, float octaves)  {
    float total = 0;

    for (int i = 0; i < octaves; i++)  {
        frequency = frequency ^ i;            // or frequency *= 2; ?
        amplitude = amplitude ^ i;

        total = total + SimplexNoise.raw_noise_3d(x * frequency, y * frequency, z * frequency) * amplitude;
    }

    return total;
}


texts: Soft-restart tampers with physics determinism, resulting in different results

texts:
Updated question
I have a Spawner entity that spawns my Rollables:
// Spawner.cs
public abstract class Spawner : MonoBehaviour
{
    public abstract T Spawn<T>(T prefab) where T : Component;
}

// PositionSpawner.cs
public abstract class PositionSpawner : Spawner
{
    public override T Spawn<T>(T entity)
    {
        T spawnedEntity = Instantiate(entity);
        spawnedEntity.transform.position = transform.position;
        spawnedEntity.transform.rotation = transform.rotation;

        return spawnedEntity;
    }
}

// RollableSpawner.cs
public sealed class RollableSpawner : PositionSpawner
{
    public Rollable Spawn(Rollable entity)
    {
        Rollable rollable = base.Spawn<Rollable>(entity);

        Restore(rollable);

        return rollable;
    }

    public void Restore(Rollable entity)
    {
        Quaternion r = transform.rotation;
        Vector3 p = transform.position + transform.up * (entity.Radius + 0.05f);

        entity.transform.rotation = r;
        entity.transform.position = p;

        entity.Rigidbody.rotation = r;
        entity.Rigidbody.position = p;

        entity.Restore();
    }
}

The Rollable though, is quite a big one and somewhat coupled with RollableCollider - found, fully, here.
The Restore method:
public void Restore()
{
    rigidbody.velocity = Vector3.zero;
    rigidbody.angularVelocity = Vector3.zero;
    rigidbody.Sleep();

    inAir = Drowning = false;

    Speed = 0f;
    Altitude = 0f;
    UnShift();

    UpdateDirectionality();
    UpdateOrientedTransform();

    ClearGateEventRegistry(gateEntryEvents);
    ClearGateEventRegistry(gateExitEvents);
    ResetSoakedParts();

    StopCoroutine(sleepingRoutine);
    StopCoroutine(gateRoutine);

    rigidbody.WakeUp();

    UpdateInAir();

    sleepingRoutine = StartCoroutine(SleepingRoutine());
    gateRoutine = StartCoroutine(GateRoutine());

    previouslyBackwards = false; Backwards = false;
}

And, to reset, I am calling RollableSpawner.Restore() with a push of a button.
The problem here is that even if after reset all of the values are as expected - position/rotation are correct, velocities and everything else - the Rollable still ends up taking a slightly different trajectory each time.
Though, that's only noticeable with soft-reset.
If I am to play/stop/replay the scene - the Rollable always takes the same trajectory.
Why is it that upon soft-reset the Rollable - while having the same properties - ends up in different trajectories, yet, hard-reset doesn't?
And... how do I fix it?
P.S. As for what have I tried.. Switching Sleep()/WakeUp() to isKinematic. But to be honest, I don't even have a clue what to attempt.


texts: How do I make Unity projects portable between developers

texts:
Our team are very new to Unity but has a strong programming background. We have created a Unity project that will allow us to control a simple model (imported asset) using some scripts. The project consists of 4 packages installed from the Asset store, some customisation of those assets and then some C# scripts we have added.

How can we apply version control the project and share it between developers so that they can check out the latest copy of the project, open it in unity and work on it?

The trouble we are having is that assets installed from the store are not portable with the project folder in git. When another new developer opens the Unity project they find that the model is corrupted because they first needed to go to the Asset store and install the same assets that were installed by the developer working on the project earlier to run the install scripts of those assets. Because the project was opened without those assets being installed from the store, installing them after opening the project does not fully restore the model state and the project appears broken.

Really what we would like is a system like NuGet which installs dependency assets when the project is first opened on a new developers machine while the model customisations and scripts are carried over.

How to teams of developers work on a single Unity project?


texts: Movement / aiming algorithm in 2d / tiled based game

texts:
I'm trying to create simple 2D / tiled base game in JavaScript. Entities are able to move by any number of pixels, but only in one direction at once (can't go in diagonal way). AI for enemies is simple 'zombie movement' (if you see target - go to him).

Currently I've got problem with my shooting mechanism. In my code I've got statement which say something like this:

if (distance_to_target <= weapon_range) {
    shoot_in_current_direction();
}

As you can see on example below my problem exist when target is in range in diagonal way.
Red rectangle is 'shooter', blue rectangle is 'target', black dots are 'bullets' and black arc line is a weapon range.

My question is: how to implement restrictions which allow to shoot only if target is in good direction, but not exactly on that same x/y coordinate (allow for some margin)? Should I implement more intelligent movement algorithm (i.e A*)?

To be clear... I'm not looking for ready code but rather for some algorithm help.


texts: Character controller passes through mesh collider

texts:
I need a little help figuring out what's going on with an NPC's character controller. Here are the character controller settings for the NPC.

The problem I'm running into is that the NPC isn't walking up a slight gradient as it should; instead, it moves through the ground.

Below are the settings for the ground.

The NPC isn't on the ground- it is a few units off. Any help is greatly appreciated.

Thanks in advance...


texts:
I have this usermap from kinect's depth data (size is 320x280) and i want to display it on my game. The problem, of course it's ugly (first image) and i want to have beautiful effect like in the second image

The usermap is put on a bilboard as a texture2D and i've been thinking i should use fragment shader. I'm wondering what kind of shader techniques i should use so i can possibly make the same effect as shown on second image

Usermap: http://www.azerdev.com/darkmachine/usermap.png

Glowing man: http://www.azerdev.com/darkmachine/silhouette.jpg


texts: OpenGL Core 3.2 framebuffer rendering black on Mac OSX

texts:
I'm trying to get a 2 pass post-processing system going in OpenGL in a cross-platform manor using FBOs. I'm starting the dev on mac OSX (since in the past I've found it the most finicky to get working of windows/linux/osx), I have a toggle to toggle between using the FBO(post-processing) and not. The shaders are working, but it seems the FBO didn't load the texture unit bound to it. The following is the init code for the FBO and it's texture:

glGenTextures(1,&fboimg);
glBindTexture(GL_TEXTURE_2D,fboimg);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 512, 512, 0,
             GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);

glGenFramebuffers(1,&fboHandle);
glBindFramebuffer(GL_FRAMEBUFFER,fboHandle);

glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,fboimg,0);

GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

switch(status)
    {

        case GL_FRAMEBUFFER_COMPLETE:    cout<<"The fbo is complete\n"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT\n"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT\n"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"<<endl; break;
    }

if(status != GL_FRAMEBUFFER_COMPLETE)
{
    cout<<"status !=  GL_FRAMEBUFFER_COMPLETE"<<endl;
    GLUtils::checkForOpenGLError(__FILE__,__LINE__);
}
else
{
    //shader and VAO setup for post
    fboSetup = true;
}

Here is the render code:

//start rendering to FBO
if(postFlag&&fboSetup)
{
    glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);

}
glUseProgram(programHandle);

//start rendering scene one way or another
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glUniformMatrix4fv(mats.projHandle,1,GL_FALSE, glm::value_ptr(mats.projMatrix));
glUniformMatrix4fv(mats.mvHandle,1,GL_FALSE,glm::value_ptr(mats.modelViewMatrix));

//bind to vertex array object
glBindVertexArray(vaoHandle);
//render scene
glDrawArrays(GL_TRIANGLES, 0, 240*3 );

//do post-processing if we have it enabled
if(postFlag&&fboSetup)
{
    glFlush();
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    glUseProgram(fboProgram);

    glClear(GL_COLOR_BUFFER_BIT);

    glBindTexture(GL_TEXTURE_2D,fboimg);

    glUniform1i(glGetUniformLocation(fboProgram,"sampler0"),fboimg);
    glUniform2f(glGetUniformLocation(fboProgram,"resolution"),512,512);
    glBindVertexArray(vaoFBO);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindTexture(GL_TEXTURE_2D, 0);
}

Tried everything I can think of or find in a FBO tutorial or have read about. I don't get any errors and it returns as complete. (Also I can't seem to get it glTexImage2d a image of size width and height. says invalid values, and if I try to use GL_TEXTURE_RECTANGLE it says invalid enum :-/ but that's for a different question after I just get it working to begin with^^)


texts: When developing in Javascript, it seems useful especially for event systems to use enum-likes, but not string comparison for performance considerations (also because it doesn't protect against typos). How do you use Enums in JS? Should I switch to Typescript?


texts: How do I make a transition between two states to be slowly?

texts:
Now it's doing the first New State then it's jumping to New State 0
Instead I want it to slowly move between the two states. I want to see the animation transition slowly changing from state to state.

For example when you see a character sitting and then standing so to see the transition from sitting to standing slow.


texts: How to make camera rotation independent from frame rate?

texts:
I multiply the mouse movement by a given number to get camera rotation of a desired speed. But it only works at 60 FPS. When I don't limit the frame rate I get around 350 FPS and the camera rotation is significantly too slow.

In my calculation, I already consider the frame time.

rotateCamera(ivec2 deltaMouse, float deltaTime, float sensitivity)
{
    // apply multipliers
    deltaMouse *= deltaTime;
    deltaMouse *= sensitivity;

    // rotate camera by deltaMouse
    // ...
}

Is this approach wrong? Why isn't the mouse movement independent from the frame rate in my code? How to achieve that?


texts: Send regular keyboard samples OR keyboard state changes over network

texts:
Building a multi player asteroids game where ships compete with each other. Using UDP.
Wanted to minimize traffic sent to server. Which would you do:

Send periodic keyboard state samples every from client every to match server physics update rate e.g. 50 times per second. Highly resilient to packet loss and other reliabilty problems. Out of date packets disacarded by server. Generates a lot of unnuecessary traffic.
Only send keyboard state when it changes (key up, key down). Radically less traffic sent from client to server. However, UDP can lose packets without you being informed. So the latter method could result in the vital packet never being resent unless I detect and resend this in a timely manner.


texts: Don't understand how paddle location is tracked; using XNA tutorial

texts:
Wanting to learn how to make games, decided to use Monogame. Have pretty light programming knowledge, so I apologize beforehand for my ignorance to this surely obvious oversight.

Following a beginner's tutorial on XNA game development. It's a simple ball and paddle game that has a game class, paddle class, and ball class.

Now my problem lies in the code for the ball class.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;

    namespace BreakingOut
{
class Ball
{
    Vector2 motion;
    Vector2 position;
    float ballSpeed = 4;

    Texture2D texture;
    Rectangle screenBounds;

    public Ball(Texture2D texture, Rectangle screenBounds)
    {
        this.texture = texture;
        this.screenBounds = screenBounds;
    }

    public void Update()
    {
        position += motion * ballSpeed;
        CheckWallCollision();
    }

    private void CheckWallCollision()
    {
        if (position.X < 0)
        {
            position.X = 0;
            motion.X *= -1;
        }
        if (position.X + texture.Width > screenBounds.Width)
        {
            position.X = screenBounds.Width - texture.Width;
            motion.X *= -1;
        }
        if (position.Y < 0)
        {
            position.Y = 0;
            motion.Y *= -1;
        }
    }

    public void SetInStartPosition(Rectangle paddleLocation)
    {
        motion = new Vector2(1, -1);
        position.Y = paddleLocation.Y - texture.Height;
        position.X = paddleLocation.X + (paddleLocation.Width - texture.Width) / 2;
    }

    public bool OffBottom()
    {
        if (position.Y > screenBounds.Height)
            return true;
        return false;
    }

    public void PaddleCollision(Rectangle paddleLocation)
    {
        Rectangle ballLocation = new Rectangle(
            (int)position.X,
            (int)position.Y,
            texture.Width,
            texture.Height);

        if (paddleLocation.Intersects(ballLocation))
        {
            position.Y = paddleLocation.Y - texture.Height;
            motion.Y *= -1;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
    }
}
}

When I run the game, it functions properly. Player moves the paddle, and when the ball collides with the paddle, it bounces off.  I don't understand how the Ball class knows the paddle location though.  It's not like paddleLocation is a public variable in the paddle class.


texts: OpenGL object movement is not smooth and vibrating

texts:
In my android NDK OpenGL C++ project, I have a render method which executes every frame on draw event so this is the algorithm:

void Engine::render() {
    deltaTime = GetCurrentTime() - lastFrame;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    update();
    renderDepthMaps();
    renderMeshes();
    if (skybox != nullptr)
        shaders.drawSkyBox(skybox, camera, width, height);
    lastFrame = GetCurrentTime();
}

first I calculate the delta time between the last frame and the current frame, then I update all transformation and view matrices from input then render the scene so the game loop depends on the android draw frames, I have an object which moves over a terrain and a third person camera moves with it and rotates around it, so after the object moves for some distance it begins to flicker forward and backward, the update function for the object is:

double& delta = engine.getDeltaTime();
GLfloat velocity = delta * movementSpeed;
glm::vec3 t(glm::vec3(0, 0, 1) * velocity * 3.0f);
matrix = glm::translate(matrix, t);
glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
f = -glm::normalize(f) * velocity * 3.0f;
camera->translate(f);

If it is an interpolation issue I don't know how to make interpolation with using translate matrix to its forward vector.