texts:
I've been reading over the various chapters available at http://gameprogrammingpatterns.com, and in particular his chapter over Data Locality(http://gameprogrammingpatterns.com/data-locality.html) has raised a few questions. I've sent him out an email, but while waiting for it I figured I'd gather the opinions of others.

In the chapter, it is suggested that you would take your GameEntity class and strip everything away, sticking all of the components into an array and using a dirty bit to tell whether or not the component is active. This allows for faster iteration and avoids thrashing the cache.

However, it is also stated to avoid polymorphism in order to keep all components of some type the same size, and avoid virtual methods. Rather, for every type you would have an array.
To me, this sounds wasteful. Say I have 20 different enemies, and I allow for 100 enemies to exist at a time. That'd be 21(20 different MOBs + 1 array that would hold the entity) arrays of 100 entries, so 2100 objects just for the different enemies. And then each enemy needs a physics component, a rendering component, and maybe even more depending on the game.
If every enemy needs it's own physics and rendering component, that'd be 21 Entities + 20 Physics Components + 20 Rendering Components, all multiplied by 100(or however many entities you are allowing to exist at once). That's a lot of data for stuff that isn't going to even be used most of the time.

Wouldn't it be simpler(and smarter) to just have arrays of the base class, then stick in the needed subclass at some index? The base class would hold all the data that would need to be accessed by any of the subclasses, the subclasses would only have an overloaded Update() function. Yeah, it'd be a bit slower because then the program would have to look at the vTable over and over again to figure out which Update() function to use and not all the data in the base class will be used by every subclass, but it sounds simpler and faster than having 100+ arrays, each with 100+ members, when a large portion of them aren't even being used at any given moment. Are there any downsides to my take on it? Am I missing an important concept of data locality? What is your take / what would you do?


texts: How to make an upgrade a building and replace it with the Level 2 prefab?

texts:
I want to to have multiple prefabs like canon level 1 and then level 2.
When the player has enough coins, they can upgrade it to level 2.
I want to make a game similar to Clash of Clans so I will have many buildings that can go through different levels.
How can I do this?


texts: Creating a playlist with LWJGL and OpenAL

texts: I'd like to know how to create a playlist for the music in my games. I use LWJGL, and know a bit of OpenAL, however I can't figure out how to test for when a song is over. I want to be able to play one song after another, and I want to do that without hardcoding a timer for each song.


texts: free web library for leaderboards / achievements

texts:
I would like to know if there is any free leaderboard libraries for web games developed in HTML5/JS (as openfeint is for iPhone, Android)

I found this http://www.appmobi.com/, but it seems the leaderboard APIs which are in BETA is not free.


texts: 3D Physics Engine Collision Response: Solving Simultaneous Collisions via equation

texts:
I have been implementing a basic physics engine for a small game project I'm working on. It has very specific requirements, so I decided to try and write my own physics engine to meet them. I found this paper, which seemed to be reasonably simple, and provide answers for everything I needed.

https://drive.google.com/file/d/0Bze6mKYvrpOKYjdkODVhMTAtM2Q4Zi00NzgyLWE2YzMtN2MwZmQ4NjA3OWMw/view?ddrp=1&hl=en#

So far I have successfully implemented collision detection (using my own custom algorithm designed to suit my particular requirements), as well as the collision response (See section 2.6.2.1 on page 41 of the paper).

I have, however, become stuck on solving simultaneous collisions. The paper provides equations (see section 2.6.7.1 on page 51), but I am unable to understand or implement them.

Can someone explain how these are supposed to be implemented?

Here is my current understanding of what is presented, and why is must be wrong:

In terms of implementation, I'm not sure what they mean by "combined contact impulse," as they do not mention to term elsewhere and fail to explain what they are "combining" (Possibly the angular and linear impulse, but I'm not sure how those aught to be combined).

I am also not sure how these formulas are supposed to work. It appears in the first equation just sum the the combined impulse (whatever that is), and use that to increase the velocity, but they only add it in 1/k (where k is the number of iteration) size chunks k times. This basically just seems to result in summing the velocities. This is not physically accurate since multiple collision against the same object will be summed resulting in unrealistically strong velocities.

I'm even more confused by the next equation. It appears to add r cross n to the rotational velocity, with complete disregard for impulse magnitude. Doesn't make sense ether.

The third equation has the same problem as the first.

I feel like some kind of integration or transform needs to happen on each iteration that is not shown, but I am not sure what it should be.

Please feel free to leave comments asking for clarification. I'm utterly confused, and I would not be surprised if my questions lack a little coherence.


texts:
I am new to game development, and I have been building some game with LibGDX engine.

The following function might make you feel bad

The function I am going to show, is accepting the current rotation index of my player (player has 4 rotations, north, south, west, east). The function will return how much to jump in X to get the next tile according to his direction (angle) and the selected move (you can only select left, right or forward per turn):

public int getIncrementXForRotation(int rotationIndex) {
    switch(this) {
        case MOVE_FORWARD:
            switch(rotationIndex) {
                case Face.EAST:
                    return 1;
                case Face.SOUTH:
                    return 0;
                case Face.WEST:
                    return -1;
                case Face.NORTH:
                    return 0;
            }
        case MOVE_BACKWARD:
            switch(rotationIndex) {
                case Face.EAST:
                    return -1;
                case Face.SOUTH:
                    return 0;
                case Face.WEST:
                    return 1;
                case Face.NORTH:
                    return 0;
            }
        case MOVE_LEFT:
            switch (rotationIndex) {
                case Face.EAST:
                    return 0;
                case Face.SOUTH:
                    return 1;
                case Face.WEST:
                    return 0;
                case Face.NORTH:
                    return -1;
            }
        case MOVE_RIGHT:
            switch (rotationIndex) {
                case Face.EAST:
                    return 0;
                case Face.SOUTH:
                    return -1;
                case Face.WEST:
                    return 0;
                case Face.NORTH:
                    return 1;
            }
        case TURN_LEFT:
            switch(rotationIndex) {
                case Face.EAST:
                case Face.SOUTH:
                    return 1;
                case Face.WEST:
                case Face.NORTH:
                    return -1;
            }

        case TURN_RIGHT:
            switch(rotationIndex) {
                case Face.NORTH:
                case Face.EAST:
                    return 1;
                case Face.WEST:
                case Face.SOUTH:
                    return -1;
            }
    }
    return 0;
}

Same function for Y.

Now I looked at this, and i thought to myself.. north can be an 0, and east can be 90, and south can be 180 and west can be 270, am I right?

So there is a way to mathematically do these coordinate increment according to the angle, isn't there?

The reason I classified my player angles by `enums` is because each direction is an image.


texts: How is tile offsetting accomplished in 2d side scrollers?

texts:
The idea is to work with tiles that together make up a larger image, or world so to speak.

but im confused as to what the methods used are to offset the tiles, and whether is a good idea to draw offscreen.

For example

var backgroundScroll = 0
update() {
 backgroundScroll++
}
render() {
graphics.draw( resource: BACKGROUND, screenX: -backgroundScroll, screenY: 0)
}

while there's no tiles seen here for the sake of simplicity,
im simply emphasizing that we are drawing off screen.

As such the question is, how is this background offsetting accomplished, more specifically, without trying to render outside of the screen, as the framework may or may not know how to handle drawing to areas beyond that of the screen.

In essence the game's world will be comprised of an array of tiles

var cells[map_w][map_h]

and each cell is 32 px wide and 32px height

the idea is to scroll the map but cutting corner cells 1px per unit of speed,
but altering the logic so that no negative numbers are entered into the draw function.

I could probably figure something out on my own but i really want to hear how other people are accomplishing this rather popular task


texts: UniRx: Subscribing to ReactiveProperty condition

texts:
I'm trying to track a cold source with a contiguous range, and every example I've seen involves discrete increments or events that are already handled, so I'm vague on how to apply it.

Here's what I have:

ReactiveProperty<float> CurrentAlpha = new ReactiveProperty<float>(msg.GetComponent<CanvasRenderer>().GetAlpha());
CurrentAlpha.Where(x => x <= 0.0f).Subscribe(x =>
{
    Debug.Log($"CurrentAlpha == {CurrentAlpha} Observed");
    img.transform.SetParent(null);
    Destroy(msg);
});

I verified the alpha value, but never received notice when it reached 0. What have I mistaken?

EDIT: Found that it's actually subscribing to the value returned, which will always be 1. The value it receives is outside managed code, so there's no object property to observe, and CanvasRenderer itself doesn't observe it.

Is it possible to observe a method's return value?


texts:
I have camera rotating by dragging mouse.
 Im trying to add reset button that restart the scene to initial view.
 The rotating camera works as expected but I can't figure out how to reset it.
The scene rotating in weird directions, not as expected.

I have 2 vars - absX, absY which hold the overall change angle value from the init mode.

when reset applied:

mat4.rotate(getRotationCameraMat, degToRad(-absX/10), [0, 1, 0]);
mat4.rotate(getRotationCameraMat, degToRad(-absY/10), [1, 0, 0]);
absX=0;
absY=0;

apply the rotate:

mat4.multiply(mvMatrix, cameraRotationMat);

the camera code:

var mouseDown = false;
var prevMouseX = null;
var prevMouseY = null;

var cameraRotationMat = mat4.create();
mat4.identity(cameraRotationMat);

function handleMouseDown(event){
    mouseDown = true;
    prevMouseX = event.clientX;
    prevMouseY = event.clientY;
}

function handleMouseUp(event){
    mouseDown = false;
}
var absX=0;
var absY=0;

function handleMouseMove(event){
    if (!mouseDown){
        return;
    }

    var currentX = event.clientX;
    var currentY = event.clientY;
    var deltaX = currentX - prevMouseX;
    absX+=deltaX;
    var newRotationMatrix = mat4.create();

    mat4.identity(newRotationMatrix);
    mat4.rotate(newRotationMatrix, degToRad(deltaX/10), [0, 1, 0]);

    var deltaY = currentY-prevMouseY;
    absY+=deltaY;
    mat4.rotate(newRotationMatrix, degToRad(deltaY/10), [1, 0, 0]);

    mat4.multiply(newRotationMatrix, cameraRotationMat,cameraRotationMat);

    prevMouseX = currentX;
    prevMouseY = currentY;

}


texts: How can I determine where objects can be seen from a given perspective?

texts:
I'm wrapping my head around OpenGL ES 2.0 and I think I'm trying to do something very simple, but I think the math may be eluding me.

I created a simple, flat-ish cylinder in Blender that is 2 units in diameter.  I want to create an arbitrary grid of these edge to edge (think of a checker board).

I'm using a 3D perspective with GLKit:

    CGSize size = [[self view] bounds].size;
    _projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(45.0f), size.width/size.height, 0.1f, 100.0f);

So, I managed to manually get all of these cylinders drawn on the screen just fine.  However, I would like to understand how I can programmatically "fit" all of these cylinders on the screen at the same time given the camera location, screen size, cylinder diameter, and the number of rows/columns.

So the net effect is that for small grids (i.e., 5x5) the objects are closer to the camera, but for large grids (i.e., 30x30) the objects are farther away.  In either case, all of the cylinders are visible.


texts: Using the Oculus Rift S, I just added OVRCameraRig and LocalAvatar or OVRPlayerController and when I press play I feel like I'm not as high as I want in my vision and hands, I change the position of Y of objets to make it more higher, but it affects to everything, my guardian setup floor goes more high too and it does not match with my floor. What can I do to solve this? What should I change or modify?


texts: I'm working with a custom ScrollPane, but I can't find how to change the velocity of scrolling (not on fling action). Can anybody tell me how reduce scrolling velocity on calling setScrollY() or setScrollX()?


texts: Combining multiple sprites vs separate sprites

texts:
I have a character which can hold ten types of weapons.

Should I:

Create ten sets of animations for the character with each weapon
Create animations for each weapon, and programmatically draw them on the character

Option 1 is simpler in general, but requires more work on the artist, and results in larger game size.

Option 2, to me, is a programming nightmare...

Whats the better practice in general? Thanks.


texts: What is the best way to increase slowly object movement speed and slow down the object near the end?

texts:
There a Lerp but also SmoothDamp.
In this script I'm using SmoothDamp but why not using Lerp ? And how should I use this script with the SmoothDamp tp make slowly increasing speed at the start ? Now it's only slow down at the end but I want it also to increase slowly at the start and then slowly down near the end.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementSpeedController : MonoBehaviour
{
    public Transform target;
    private Vector3 velocity = Vector3.zero;
    public float smoothTime = 0.3F;

    void Update()
    {
        transform.position = Vector3.SmoothDamp(transform.position, target.position, ref velocity, smoothTime);
    }
}


texts:
I'm trying to write a simple program where a 3D landscape can be walked about with a basic camera. However, I've found it very difficult to do even simple collisions with my terrain. I'm wondering if anybody has encountered a similar issue before and possibly might know how to solve it a better way?

I've seen a lot of 3D collision questions, but I noticed that a lot of the answers are to approximate the mesh objects with spheres or cubes - however I find this impractical with something as complicated as terrain. I'm using a .fbx model of terrain made with blender, grabbing its entire list of vertices, finding the one closest to the camera, and trying to set the camera Y to the vertex Y + a constant. However, I keep running into a bunch of problems such as:

finding the closest vertex is difficult because if the model is too big, distances measured between the camera and the vertices will overflow some variable types, but if the model is too small, distances will often be indistinguishable and inaccurate.
my method is very slow, because the terrain has a lot of detail, so I find myself only checking every 20 vertices or so.
I end up with very bad collision detection because my method appears to be inexact and malfunctioning.

Here's some of my code, if anybody wants to see what I'm doing... (btw the d_check array is a list of vertices of the model, and C is my camera.)

    private void BasicCameraCollisionTest(int radius, int offset)
    {
        float smallest_d = float.MaxValue;
        float c_d = 0;
        int i_cache = 0;
        for (int i = 0; i < d_check.Length; i+=20 )
        {
            c_d = Vector2.Distance(new Vector2(d_check[i].X, d_check[i].Z), new Vector2(C.position.X, C.position.Y));

            if (c_d < smallest_d)
            {
                smallest_d = c_d;
                i_cache = i;
            }
        }
        C.position = Vector3.Lerp(C.position, new Vector3(C.position.X, d_check[i_cache].Y + radius + offset, C.position.Z), 0.02f);
    }

If anybody could point me in the right direction, I'd be very grateful. Thanks!


texts: OpenGL approach to depth-testing-like combination of a large buffer of fragments

texts:
I have a depth buffer and color buffer created by another effect. The buffer is more than double my screen size. It is not rendered from geometry, but as a whole it resembles a rendered scene with an ortho projection. I can't generate this data w/ any other projection. I'm trying to redraw the scene in two-point perspective. This means each fragment from the orthographic data will be skewed and translated based on the depth value.

If I render a fullscreen quad, each fragment will not know how or where to sample from the original buffer. It seems like I the sources have to assign themselves to destinations, rather than a destination gathering sources.

Impractical or incomplete solutions:
- Generate a tri or point for every pixel in the source buffer, and actually rasterize them with depth testing. This is really slow, but it could be possible to generate the vertices in a compute shader or something? We're still dealing millions of tris for an average screen. I'm skeptical that this is the real solution.
- Something with SSBO and atomicMax. It seems like you can only compare your actual data, so I would have to pack my colors with depth values somehow.

This seems like a fairly fundemental operation, so I'm hoping there is some canonical technique or opengl extention that does this sort of thing for me well. Even a name for this operation might help me find existing literature.

The final solution must be realtime for typical screen sizes. C++/OpenGL.


texts: Does dynamic DSP exist in any game engine today?

texts:
I'm interested in changing audio in my games and adding things like distortion (or you name it) to them dynamically.

For instance: Increase the distortion of a song playing from a radio the closer a player walks to it.

Basically, I want to know if this ability exists in any game engines today. I've programmed my own DSP effects in the past and woukd like to use them on my audio for fun.

What I am not talking about is built in 3d sound or just simply triggering a myriad of pre made sound + effect combinations.


texts: How to create art assets for a 3d avatar editor

texts:
I am currently prototyping an idea for an iPhone game. I'd like to create an avatar editor inside the game so that the player can create a 3d avatar face and modify certain features (using slider controls), such as nose shape, eye color, mouth size, etc. This has been done in several games, but what I'm looking to do would be fairly cartoon-ish/caricature-ish, similar to the Mii editor on the Nintendo Wii (http://www.myavatareditor.com/). I'd also like the final result to have the ability to use some canned animations, such as simple speech animations, smiling, frowning, etc.

I am not an artist, so I would be unable to create these assets, but what kind of effort is required for an artist to create the 3d models necessary for this type of game? Also what mechanism would be required to tweak the face's characteristics? Would you use bones or morph targets? How would the final result be animated? Would facial animation use bones or morph targets?

I've seen several tools that do this sort of thing too, such as FacialStudio. Are there any facial generation tools out there you'd recommend for generating some base content for this game, or should I just hire an artist to do this type of work.

Thanks!


texts: Parent variable inheritance methods Unity3D/C#

texts:
I'm creating a system where there is a base "Hero" class and each hero inherits from that with their own stats and abilities. What I'm wondering is, how could I call a variable from one of the child scripts in the parent script (something like maxMP = MP) or call a function in a parent class that is specified in each child class (in the parent update is alarms() in the child classes alarms() is specified to do something.)

Is this possible at all? Or not?

Thanks.


texts:
So I've been making this game called The Necromancer and (quick note, I am still working on the game. Also, I know this sounds similar to this question, but my question is for the general process) I wanted to publish on the Steam Store. However, I don't know what the process is, as in what you do to get your game posted on Steam. Also, how would I get a few files, and somehow put it in a virtual package that I can give to Steam. I just feel rather confused on the subject.

Thank you for your time


texts: Game programming books that don't teach programming?

texts:
I am an normal programmer with about 3 years of experience, who is interested in getting into game development. The problem that I face is that when I look at these "beginner" books, most of them teach basic programming skills, and I don't have the patience to sit through it or find them worthwhile. But, when I look at more advanced books, they're over my head, and once again, fruitless to me. What I'm looking for, are books that explain the nitty-gritty internals of games, but at a more reasonable level.

For example, I'm very familiar with all kinds of data structure (hashes, trees, linked lists), and with many common algorithms (sorting, searching), but I wouldn't know how to, say, implement collision detection effectively. I also have experience using foreign libraries, so I know how to use documentation to learn an API, so I don't need a "Learn to use X" book either.

Personally, I don't care what platforms/languages/libraries are used in the books, since I'm comfortable in many languages, but the game I'm looking at making would use Javascript and the HTML5 canvas.

Any suggestions? Any that are free?

P.S. I should note that my level of mathematics and physics is relatively low, and a book that gently integrated those things would be a plus.

EDIT: I should mention that I'm interested in 2D programming, and at this point I don't really care for 3D yet.


texts: Long occluding geometries in Resonance Audio for Unity

texts:
I'm currently looking into using resonance audio (https://resonance-audio.github.io/resonance-audio/) for accurately modelling the audio for an environment that approximates to a long corridor with a series of bends. I want to have a sound at the end of this corridor that the user can hear at any point in the corridor based on the sound reflections along the corridor.
I have tried a few of the options presented by Resonance Audio:

Placing reverb probes along the corridor. This seems like the ideal option, however a reverb probe will only apply its baked in reverb profile to sound sources inside the probe. If I try to make the probes larger then they seem to take into account all of the geometry of the corridor at once and things get exceedingly echo-ey and consistent regardless of where I am in the corridor.
Turning the corridor model into an audio room. This isn't apropriate as it has many of the same issues as a large reverb probe, and also doesn't actually model the space itself.

Has anyone had any experience with hearing distant sounds in Resonance Audio environments like this? At this point I have a feeling that Resonance Audio is just not built for this particular situation.


texts: Unity : Orthographic Camera is not Occlusion Culling?

texts:
In the scene where the occlusion culling is done as desired,

When I change the camera to orthograhpic, occlusion culling is not done.

(Look at the sphere the red arrow points to on the right)

What should I do?


texts:
Is it legal to use car manufacturers' names in a game?

For example:

to describe Audi's quattro drive system?
to display a rendering of an Audi?
to include a photo (to which I have rights) of an Audi?


texts: Multiplayer game with Cocos2d-Javascript and Node.js

texts: It is possible to make a multiplayer browser based game using cocos2d-javascript + node.js? If so, is there any tutorial about that?


texts: How do i draw sprite on fixture position?

texts:
b2BodyDef bd;
    bd.position.Set(1700 / sfdd::SCALE, 150 / sfdd::SCALE);
    bd.type = b2_dynamicBody;
    b2PolygonShape squareShape;
    squareShape.SetAsBox(70 / sfdd::SCALE, 13 / sfdd::SCALE);
    m_body1 = m_world->CreateBody(&bd);
    m_body1->CreateFixture(&squareShape, 100);
    squareShape.SetAsBox(38 / sfdd::SCALE, 16 / sfdd::SCALE,b2Vec2(-54/sfdd::SCALE,-30/sfdd::SCALE),90*DEGTORAD);
    m_body1->CreateFixture(&squareShape, 20);

    squareShape.SetAsBox(30 / sfdd::SCALE, 10 / sfdd::SCALE, b2Vec2(60 / sfdd::SCALE, -20 / sfdd::SCALE), 90 * DEGTORAD);
    m_body1->CreateFixture(&squareShape, 100);


texts:
I am developing a game and have a clear vision of how it works, what key features it has and how it should look alike.

But when it comes to introduce the designer I feel a little bit lost. I have no graphics talent so I try to pitch it with mockups and text.

But I guess there are better ways or methods to get it on paper - how would they look like?


texts:
First of all a little premise: I'm following this tutorial on YouTube for procedural 2d cave generation in unity using cellular automata and I'm extending it in order to make caves in all three dimensions. With this approach, caves are based on a 3d matrix where if a cell value is 1 it is a wall and if 0 it is an empty space.
The "rooms" created, after being logically connected, need to be "physically" connected by making a path of zeros in the 3d matrix and the tutorial explains how to do this in 2d.

Can you, please, suggest me the approach on how to draw a discrete line (of zeros in this case), in a 3d matrix, that goes from point A to point B?

I'll attach a screen of a map example where rooms are drawn with cubes and red lines are the logical connections.


texts: Unity: How to Retrieve Port Number Used for Test Build

texts:
SUMMARY
I am looking for a straightforward way to get the port number that the Unity editor is using to serve WebGL test builds after the build's browser window has been closed.
I'm supporting Unity students who are not computer savvy. I'd like to know if there's an easy way to get this information from the editor itself, short of rebuilding the project.
DETAILS
To test my Unity WebGL project from the Unity Editor, I select the menu "File > Build and Run."

Once the project is built, a Chrome window opens with a location of the form "http://localhost:53587/", where 53587 is a random port number.

WHAT I HAVE TRIED
Google searches haven't given me an easy way to discover this port.
Using Window's Resource Monitor, I can find all the ports unity test servers are listening on, but this method requires many steps and external tools. I'd like know if there is a way within Unity to discover this information.
Complicated Method

Press Ctrl+R to open the Run window.
Type resmon.exe and press ENTER
Select the Network tab
Select the Listening Ports bar
Sort on image by clicking on the image column header
Search for image mono.exe
Get port number(s) from Port column.

This is relatively complicated, Windows-specific method and it's inexact; it can return multiple instances of test builds being served.  I'd like an easy way of discovering the port being served for the project currently being edited.


texts: If my game will use say 100mb of raw memory for textures, would it be a good idea to put all of them in srv array, bind once and leave it for the rest of the program so that I won't have to bind them ever again and thus save some processing power? I'm targeting gpus with at least 2gb of vram.


texts: How to connect two Iphone/ipod/ipads for gameplay over local wifi network?

texts:
I would like to add the option to play against another person over my wifi network in my pong game. How do I make this happen?

Also, I would like to know how to be able to have 4 players at the same time like I would if I make a monopoly type game or something similar.

I'm a newbee so please point me in the right direction or show me some code I can use for this and study.
Thanks guys
David


texts: How to tune steering behaviours to pick the best target around obstacles?

texts:
I want to chase an enemy, but there are obstacles in the world. Imagine there's an obstacle stopping me reaching the closest enemy, but in another, unobstructed, direction is another enemy but at a further distance:

***************
E ** P        E
***************

* - obstacle
E - enemy
P - player

My enemy-chasing behaviour returns a vector pointing towards the left-most enemy, and my obstacle avoidance behaviour returns a vector pointing to the right, away from the obstacles. At some point they balance out and I have stalemate!

This could all be avoided if there was an elegant way of choosing the other enemy at the beginning.

Is this a common problem in steering behaviours? How is it regularly solved? I may have a lot of enemies, so pathfinding to each first may be inefficient.


texts:
I am using Unity Pro 4.2.1f4 and I always have this sort of glitch. This is due to the shadows and the bias. Even with a low bias this is happening.

I've found a thread that talks about that but I don't find it anymore.
What is the technical reason about that issue ?
Where does it come from ? Is there a way to avoid/minimize that problem ?

Thanks a lot.


texts: Unable to save player data in a binary file within Update() method

texts:
I'm trying to save player life within a binary file in Application.persistenceDataPath. I've written a method to store the player life:

  public void SaveLife()
     {
         BinaryFormatter bf = new BinaryFormatter ();
         FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
         PlayerData data = new PlayerData ();
         data.savedLife = life;
         bf.Serialize (file, data);
         file.Close ();
     }

The problem is that when the SaveLife() is called OnApplicationQuit it works. Instead, if I call it within an Update() method of a class, it doesn't work.

The Update() method is called when a certain event is triggered:

void Update()
{
    if (life < 20)
    {
        if (//certain event is triggered)
        {
            SaveLife();
        }

        lifeTimer -= Time.deltaTime;
        if (lifeTimer <= 0)
        {
            ResetLife ();
        }
    }

}

The container class for the data is

[Serializable]
 class PlayerData
 {
     public int savedLife;
 }

What could be the problem?


texts: 2D procedural veins/cumps of weighted ores/rocks

texts:
I'm evaluating methods for generating "clumps" or "veins" of rocks in a 2D top-down procedural game. Obviously the most common suggestion is to use various types of noise, but I feel like noise (alone) won't achieve what I'm after.

I've used a combination of voronoi and perlin noise because it's easier to generate "regions" of different noise. I can more easily turn these areas into "veins" of rocks or something than I could be using a "heightmap" alone - heightmaps tend to be more swirly/cloud-like.

With a high threshold and some rounding, I can turn this into a mask that works well for veins:

Changing the spacing and scale is as simple as toying with the math/threshold.

The difficulty lies with choosing which "rock" (or "ore") will fill each vein. Primarily, this is thanks to the fact that my rocks are weighted. Veins of rare rocks should not be common.

I currently map the original voronoi cell value to a specific rock, which  forces each vein to be a single type, but can't be weighted. As you can see in picture #1, there's a fairly even distribution of each shaded area.

So either, I need a new way to choose a weighted random rock type for each vein, or I need a new way to place veins.

Minecraft is a good well-known example of what I need, except I work in 2D:

Regularly distributed ore veins
Veins of common ores are found more often and are typically larger veins
Veins of rare ores are harder to find, and are smaller in size

Noise alone just can't seem to produce these values. What else can I try?


texts: MonoGame.Extended.Tiled: Get layers for Vector2 location without iterating over all tiles? Extended

texts:
I am trying to get the layers (or better, a special object layer) which contains a Vector2 location from a TiledMap, I know I could iterate over those, but I do not want to. How would I do that?

Thanks!

PS: I already asked at the MonoGame.Extended forums, but I may not get an answer there. That's why I'm asking here, too.


texts: Raycast in Unity for ground detection returns false while touching ground

texts:
I'm using a raycast to detect the player's distance to the ground for a hovercraft game.

The raycast works correctly (returns true and also returns the distance to the first impact) until the moment the craft actually touches the ground.  When the player hits the ground, the raycast should theoretically return true and return the distance as near 0f.  Instead, it returns false, meaning the raycast isn't colliding with anything over the length of the ray.  As a result, it can't find the distance.

I'm having a hard time troubleshooting this, and I wonder if anyone can lend a fresh pair of eyes.

Ray ray = new Ray (transform.position, Vector3.down);
RaycastHit ray_result;
bool hit_ground = Physics.Raycast (ray, out ray_result, optimal_vertical_distance * 2);
if (ray_result.distance < optimal_vertical_distance && vertical_force < max_vertical_force)
  {
  vertical_force += vertical_acceleration;
  }
if ((!hit_ground || ray_result.distance > optimal_vertical_distance) && vertical_force > min_vertical_force)
    {
    vertical_force -= vertical_acceleration;
    }
  }
body.AddForce (Vector3.up * vertical_force, ForceMode.Acceleration);

The only time hit_ground worked correctly was when I increased the thickness of the floor from 2 units to 4 units and set the ray to start from 2 units above the craft instead of from the craft itself.  I don't understand why it works, though.  However, in that example, ray_result.distance seems to be locked at -1.10999, regardless of how far away the craft is.


texts: Strange if-else branching behavior in a fragment shader

texts:
In my fragment shader I have passed an uniform int uLightType variable, which indicates what type of light is in usage right now. The problem is that if-else branching does not work correctly - the fragment shader performs instructions in every if statement block.

if (uLightType == 1) { // Spotlight light type
    vec3 depthTextureCoord = vDepthPosition.xyz / vDepthPosition.w;
    shadowDepth = unpack(texture2D(uDepthMapSampler, depthTextureCoord.xy));
}
else if (uLightType == 2) { // Omni-directional light type
    shadowDepth = unpack(textureCube(uDepthCubemapSampler, -lightVec));
}

In the case when uLightType equals 1, unless I comment out the content of the second if block, it assigns an another value to shadowDepth.

Also while uLightType equals 1, when I remove the second 'if' block and change == to != like in the sample code below, nothing happens (which means that uLightType really equals 1).

if (uLightType != 1) { // Spotlight light type
    vec3 depthTextureCoord = vDepthPosition.xyz / vDepthPosition.w;
    shadowDepth = unpack(texture2D(uDepthMapSampler, depthTextureCoord.xy));
}

Also, when I manually create an int variable (which is not an uniform) like this: var lightType = 1; and replace uLightType with it in the if-else branch, everything works fine, so I guess it have something to do with the fact that uLightType is the uniform.


texts:
I've finally got interpolation working to 'smooth' out movement, however it doesn't seem to work for objects that are rotating (around their own center) - when I try to do this, the objects in question 'wobble'.

Note: I'm not talking about interpolating the actual rotation but rather the movement of a rotated object

So, let's say I have an object moving from left to right.  Using the code below (with interpolation), it moves nice and smoothly.  However, after rotating the object (let's say by 45 degrees, but this could be any angle), it's no longer moving smoothly, it still moves along it's path (left to right in this case) but it's no longer smooth.

Main Game Loop

@Override
public void onDrawFrame(GL10 gl) {

    //Grab time
    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime;
    if ( frameTime > (dt*25))
        frameTime = (dt*25);

    currentTime = newTime;

    accumulator += frameTime;

    //Save game-state and update logic
    while (accumulator >= dt){
        saveGameState();  //Back up positions before updating them
        updateLogic(); //Update logic
        t += dt;
        accumulator -= dt;
    }

    //Get the amount to interpolate by
    interpolation = (float) (accumulator / dt);

    //Interpolate positions and render
    interpolate();
    render(interpolation);
}

Rotation Code

public void rotate(float x, float y, float angle){

    //Rotate the quad
    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, angle, 0, 0, 0.1f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);
}

Edit

OK so it appears this is the problem:

During logic update, sprite is moved and rotates it around it's center (using it's new/current X and Y to calculate it's center).
Get's to render()
Render method interpolates position creating new 'throwaway' coordinates at which object should be drawn
Render method draws sprite at it's 'render' x and y coordinates
Logic update moves and rotate around it actual x and y - not it's 'rendering x and y
and so on

So as you can see, it's being rotated, not around the coordinates that it's been drawn at but at it's actual coordinates.  I can't rotate it around it's render coordinates, because the rotation is done within the logic update, not during the render call, therefore, it would be rotating it around it 'old' render position, not the next one and I won't know the new render coordinates until the next render call which means.........

That the only way I can do this, is to actually translate / rotate the sprite within the render routine and not the logic routine.

I've tried this and it works, but not sure I'm happy about piling more 'logic' into my render routine.

Is this an 'acceptable' model?  How else can I achieve rotation while keeping the object nicely interpolated?!


texts: Problem with repeating objects in array when already in the array

texts:
When the player move forward then paint is instantiate and stored in the array, even if the paint is already in the array it will again be stored in the array.

But I don't want to repeat any paint in the array.

public GameObject[] array;
public GameObject paint;
int temp = 0;
private RaycastHit hit;

public float speed = 10f;
public Text levelText;
public GameObject paint;
float maxdistance = 0.51f;
Vector3 newtargetposition;
bool pos;
private void FixedUpdate()
{
      if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward,out hit, maxdistance))
      {
        if (hit.collider.gameObject.tag == "Obstacle")
        {
            move = false;
        }
     }
    if (move)
    {
        PlayerMove();
    }

public void PlayerMove()
{
    if (move)
    {
      vector3 positions = transform.position + new Vector3(0f, -0.5f,0f); //when player move then paint instantiate y position

        array[temp] = Instantiate<GameObject>(paint, position, Quaternion.identity);
        temp++;

        newtargetposition=position;
        Debug.Log("newtargetposiiton:" + newtargetposition);

        if (temp == 150)
        {
            if (newtargetposition == position)
            {
                //what can i do here
                //i dont want to paint here because position store in newtargetposition,it is repeat
                //array[temp]--;
                Debug.Log("newtargetpositions:" + newtargetposition);
                //temp--;
            }
            gameOver.SetActive(true);
            SceneManager.LoadScene(1);
        }
    }
}

when player move forward store position in array

when player move back already fillup position again store in array


texts:
I'm trying to get some hands-on experience with 3D visual effects on videos. Similar to those AR apps, I want to add a 3D model with effects, say a dragon, to a video. Something like this famous demo:
https://youtu.be/u5hQpRbHERg
But I don't really want to make it this fancy with camera tracking. I like to start with the simplest approach- probably just placing a dragon on the field (like its last scenes) with fixed camera.
What's the best way to do it? Some tutorials would be very helpful.


texts: Unity built app crashes when using particle system

texts:
I have scenes with some basic flame effect. Its max particle count is 20 and there are not more than 4-5 instances active on the screen at once. I even checked the profiler but the memory usage was around 150 MB maximum.

Given these, all runs fine in the editor but once the particles become visible, the game crashes every time. I tested this on a virtual Nexus tablet.
I'm using Unity 2017.1.0p4. If anyone has encountered an issue like this, I'd appreciate any help to get around this.

EDIT: the built game crashes on PC as well (made a final build for PC, using the same PC).

EDIT2:

So I was able to trace the issue back to the few following lines:

var mf = transform.parent.gameObject.GetComponentFromParentRecursive<MeshFilter>();

if (mf != null && mf.mesh != null)
{
    var sh2 = system.shape;
    sh2.mesh = mf.mesh;
    return;
}

public static class GetComponentRecursive
{
    /// <summary>
    /// Returns the first Component (T) found on the parent or its children
    /// = the gameobjects on the same level as this is called on.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="g"></param>
    /// <returns></returns>
    public static T GetComponentFromParentRecursive<T>(this GameObject g)
        where T : Component
    {
        if(g.transform.parent.GetComponent<T>() != null)
        {
            return g.transform.parent.GetComponent<T>();
        }
        else
        {
            foreach (Transform c in g.transform.parent.transform)
            {
                if(c.GetComponent<T>() != null)
                {
                    return c.GetComponent<T>();
                }
            }
        }
        return null;
    }
}

Please bear in mind that GetComponentFromParentRecursive works, can use it for sprites, no harm done. When I comment out the first few lines, it doesn't crash(just lost functionality).

Any ideas why this might cause a crash? And only in built game?


texts:
I am trying to create a little fun 3D game in XNA, but I am having some problems with scaling my models. I use models from random sites, so my battleship is for an example 10 times larger than my planet.

I thought I had found out how to scale my model, but it does not show up when I do, or the coordinates get really messed up. Is there a way to scale my models but still keep the same position system?

Here is my model base class.

public class BaseModel
{
    protected Matrix world = Matrix.Identity;
    protected Matrix RotationMatrix = Matrix.Identity;
    protected Model model;
    protected float scale = 1.0f;
    protected Vector3 direction;

    public Vector3 Position
    {
        get
        {
            return world.Translation;
        }
        set
        {
            world = Matrix.CreateTranslation(value);
        }
    }

    public BaseModel(Model model, Vector3 position, float scale = 1)
        : this(model, position, Vector3.Zero, Matrix.Identity, scale)
    {
    }
    public BaseModel(Model model, Vector3 position, Vector3 direction, float scale = 1)
        : this(model, position, direction, Matrix.Identity, scale)
    {
    }
    public BaseModel(Model model, Vector3 position, Vector3 direction, Matrix rotationMatrix, float scale = 1)
    {
        this.model = model;
        this.Position = position;
        this.direction = direction;
        this.RotationMatrix = rotationMatrix;
        this.scale = scale;
    }

    public virtual void Update(GameTime gameTime)
    {
        world *= Matrix.CreateTranslation(direction);
    }

    public virtual void Draw(GameTime gameTime, Camera camera)
    {
        Matrix[] modelTransforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(modelTransforms);
        Matrix wworld = GetWorld();

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = modelTransforms[mesh.ParentBone.Index] * wworld;
                effect.View = camera.view;
                effect.Projection = camera.projection;
            }
            mesh.Draw();
        }
    }

    public virtual Matrix GetWorld()
    {
        return RotationMatrix * world * Matrix.CreateScale(scale);
    }

    public virtual Model GetModel()
    {
        return model;
    }

    public virtual bool CollidesWith(Model otherModel, Matrix otherWorld)
    {
        // Loop through each ModelMesh in both objects and compare
        // all bounding spheres for collisions
        foreach (ModelMesh myModelMeshes in model.Meshes)
        {
            foreach (ModelMesh hisModelMeshes in otherModel.Meshes)
            {
                if (myModelMeshes.BoundingSphere.Transform(
                    GetWorld()).Intersects(
                    hisModelMeshes.BoundingSphere.Transform(otherWorld)))
                    return true;
            }
        }
        return false;
    }
}


texts: How to make overlap detection more accurate?

texts:
I have a project where there are two types of warrior, red and blue.

When they overlap, both are destroyed, or at least that is what should happen.

Red Warrior Blueprint (code of destruction):

This overlap is not detected. I put an impression right after the Cast To and it does not appear, so the event is not detected.

Which makes me think of another question I asked, maybe I have found the answer for it (Error detecting collision with another instance of the same actor?).

Capsule Collision of Warriors:

I had a similar problem in the collision of the red warrior with a tower, in order to have the detection of the overlap I had to greatly increase the capsule collision of tower:

It's practically a sphere.

The correct title of the question should be => How to make overlap detection more accurate without having to increase the collision box?

But I do not rule out that increasing the collision box is not the best way to detect overlap, I just want you to explain why (if it is).

EDIT 1 (attempt based on Stephen's comment)

I put an impression when the cast fails.

Red Warrior Blueprint and Blue Warrior Blueprint (respectively):

Result in game:

Test made with capsule in size (sclae) => x = 1.5, y = 1.5, z = 1.5.

EDIT 2 (Event image)

Image to show how the overlay is called:


texts:
I have terrain being rendered in my project using VBOs in OpenGL. I would like to apply some Frustum Culling but have no idea how to access each polygon as its drawn to check if it is in view. I think this is where octrees come into play but I have no idea how this is really done. Does anyone know a good tutorial on how to do this specific thing or have some pseudocode for me?

Thanks in advanced!


texts:
I am in process of developing a small game where a space-ship travels through a layer (doh!), in some situations the spaceship comes close to an enemy space ship, and the whole layer is zoomed in on the two with the zoom level being dependent on the distance between the ship and the enemy. All of this works fine.

The main question, however, is how do I keep the zoom being centered on the center point between the two space-ships and make sure that the two are not off-screen?

Currently I control the zooming in the GameLayer object through the update method, here is the code (there is no layer repositioning here yet):

-(void) prepareLayerZoomBetweenSpaceship{
    CGPoint mainSpaceShipPosition  = [mainSpaceShip position];
    CGPoint enemySpaceShipPosition = [enemySpaceShip position];

    float distance = powf(mainSpaceShipPosition.x - enemySpaceShipPosition.x, 2) + powf(mainSpaceShipPosition.y - enemySpaceShipPosition.y,2);
    distance = sqrtf(distance);

    /*
        Distance > 250 --> no zoom
        Distance < 100 --> maximum zoom
     */
    float myZoomLevel = 0.5f;
    if(distance < 100){ //maximum zoom in
        myZoomLevel = 1.0f;
    }else if(distance > 250){
        myZoomLevel = 0.5f;
    }else{
        myZoomLevel = 1.0f - (distance-100)*0.0033f;
    }

    [self zoomTo:myZoomLevel];
}

-(void) zoomTo:(float)zoom {
    if(zoom > 1){
        zoom = 1;
    }

    // Set the scale.
    if(self.scale != zoom){
        self.scale = zoom;
    }
}

Basically my question is: How do I zoom the layer and center it exactly between the two ships? I guess this is like a pinch zoom with two fingers!


texts: Starcraft II Galaxy Editor - Eventdefinition

texts:
I can create an Action with parameters using an Actiondefintion.

But how can I create an Eventdefinition ? I'd like to make an Event that is 'called' when a Unit, that is saved in a variable, dies. Like an Event called 'My unit dies'.

The  desired behavior is the following:

Called when a unit defined in a variable dies
the deceased unit should be returned by 'Triggering Unit()'
the owning player of the deceased unit should be returned by 'Triggering Player()'

I hope you get my point,
Thanks


texts: Why should I always consider creating and using object pools instead of instantiating the new object on the fly?

texts:
I have read about this pattern several times (from a best-practices perspective):

  Memory Allocation: Instead of instantiating the new object on the fly, always consider creating and using object pools. It will help to less memory fragmentation and make the garbage collector work less.

However, I don’t know what it actually means. How can I implement it?

For example, I can instantiate a GameObject using the Instantiate method of Unity?

Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity);

Is this use discouraged? What else can it mean?


texts: How can I generate a simple river surface seen from above, in a browser game?

texts:
I'm developing my first browser-based game, a very simple signup gamification where users become captains of boats, and their referred friends join the boats. The boats race to a finish line.

There is only one view, bird's eye, that shows the boats on a river. To simplify things further, I thought I would keep the boats fixed, and have the river flow from right to left. Here's the Codepen I have so far:

How can I make the river animation look more immersive? I remember after playing Chronos (video) or River Raid  back in the day for a while, when I'd move my eyes off the monitor, my vision would "flow" in the other direction for a while - that's how good the effects were.

One idea I had was to use a perfectly looping background GIF, so that the eye anchors on the continuously moving background, and the boats appear to move the opposite way.


texts: How can I stop this fixed update from executing

texts:
so I want this FixedUpdate() Method to stop executing when the Method OnMouseDown() is executed.
A bool doesn't work a if() statement also doesn't work
Please use my whole code
Please help :)
Thanks,

 private void FixedUpdate()
    {
            int random = Random.Range(1, 4);
            if (random == 1)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.green;
            }
            if (random == 2)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.blue;
            }
            if (random == 3)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.yellow;
            }

    }
    private void OnMouseDown()
    {
        shouldexecute = false;
    }


texts: What technology does Starcraft 2 use render its maps?

texts:
I've got a map that is being procedurally generated at run-time and I'm currently investigating methods of rendering this map.
I've taken an interest in the look of Starcraft 2 and I'd like some advise on what methods it employs to achieve it. Secondarily, I'd like to see any tutorials, articles, or even source code examples if possible.

There are a couple of main things I'd like to get some advise on, but please also feel free to suggest anything else that could help me.

Snappable Tilesets - A typical starcraft map seems to consist of a tileset of models that one can snap together to create the cliffs, ramps and other elevated terrain. What methods do they employ to make them look so natural? What I mean is, its very hard to spot repetition.
Terrain Textures - The terrain textures are so varied and even dynamic (Zerg creep). What methods are used to do this?

Thanks.


texts: Does anyone know where I can find a version of the farseer physics engine compiled for MonoTouch, or do most people just download a windows version from codeplex and attempt to build their own solution?


texts: Are there benefits to stage selections where only the appearance changes (i.e. Street fighter, King of fighters etc.)?

texts:
I'm not really sure if it's a good value add seeing as it would entail asset generation.

The only value I see in it would be for variance but even that would wear thin really quickly.

Clarification: i.e. Backgrounds that don't add game play related features, just appearance changes.


texts:
I wanted to know how to tint a (Buffered)Image in Java

With "tinting" I mean that black pixels stay black and grey/white pixels become the colour I want. Of Course not all pictures are grayscale

I tried to paint the Image with 50% Alpha colour, but the results are not satisfying.

Does someone know a Solution for this? Here you can see what I want:

The bottom right picture is, What I have with 50% alpha colour. the Top Right is, what I want.

A somehow linked question to this:
Is painting the image via  setRGB() for each pixel faster than BufferedImage.getGraphics() and paint on the Graphics Object?


texts: How do I get the player's position in Roblox Studio?

texts:
In Roblox Studio, I have this code in a script file:

while true do
    wait(0.01)
    local PlayersService = game:GetService("Players")
    local players = PlayersService:GetPlayers()
    for i, player in pairs(players) do
        print(player.Name)
    end
end

This successfully prints the player's name many times per second. However, I would like to know how I can get other properties, such as the player's position. player.Position doesn't work, and I have no idea what options are available because autocomplete is not working when I type player.. What properties are available on player and how do I get the position?


texts: Effect of vertex winding on normals and shading

texts:
I have implemented a Phong and Gourand shader for a triangle mesh that is being imported from an STL file. It appears to be working fairly allright but some triangles seem to be what I can only describe as upside down due to lack of better wording. This effect is visible in both shading models albeit a bit smoother in Phong. Here is an example:

On something basic like a cube the rendering is perfect. I am no expert but from what I have read, I am lead to suspect that perhaps the winding of the vertices in the mesh might be causing normals that are somewhat incorrect. Could this be possible and if so, how does one correct for that?

The effect of interpolating the normals by either division or by area weight does not really make too much of a difference. I can also confirm that the normals that I am calculating are basically the same as those that come with the STL as calculated by FreeCAD. The manually calculated normals are slightly better though because they are area weighed. They are calculated as follows:

glm::vec3 e1 = vecs[1] - vecs[0];
glm::vec3 e2 = vecs[2] - vecs[0];
faceNorms[i] = glm::cross(e1, e2);

with "vecs" being the 3 points of my vertices. I then sum up all these area-weighed normals for each face that uses a normal and finally normalize that.

PS. FreeCAD renders the mesh in a "flat" fashion and I guess thereby avoids this issue but unfortunately rendering "flat" with GLES 2.0 is a bit of a performance waste from what I have read.


texts: How important is understanding Software Project Management for an indie?

texts:
I ask this because I'm curious to know from people who actually support themselves by making games, if their project management skills contribute to determining the success of a project?

I also have this feeling for some reason that having too much project management can strangle the creative process. Maybe there is a way to prevent that from happening. I don't know.

Thanks to all that reply.


texts:
I'm trying do get a curved plane for an oldschool monitor but have still no clue how to achive this, even not after hours of searching with Google.

This is what I currently have and I need to curve this plane to look like the curved screen of an tube monitor.

Any ideas how I can achieve this?
Thank you in advance! :)


texts: Best practices for client-server communication in an online Android game

texts:
I'm developing an online RPG game for my "Object-Oriented Programming" module laboratory project. The client part must be written in C#, also using Unity 3D as a graphics engine.

The problem is that I don't know how to make the client-server communication rapid. How to achieve that every player sees other players' actions in real time on his device.

I want to get some recommendations on how to implement the client-server communication so that everything happens very quickly, i.e. when some player changes his position in a game, this change is immediately sent to all the other players' devices.

Of course, I also want to save all the players' current states in a database, so that they start where they left off the last time they logged out.

For the server side development, I'd prefer linux environment, but the language in which the server part will be written doesn't really matter to me. I just want it to be very fast.


texts: AndEngine GLES2 - getting Black screen on emulator 4.1

texts:
I'm new in andengine . I create following code

public class MainActivity extends BaseGameActivity {

static final int CAMERA_WIDTH = 800;
static final int CAMERA_HEIGHT = 480;

public Font mFont;
public Camera mCamera;

//A reference to the current scene
public Scene mCurrentScene;
public static BaseActivity instance;

public EngineOptions onCreateEngineOptions() {
    instance = this;
    mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

    return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
}

@Override
public void onCreateResources(OnCreateResourcesCallback arg0)
        throws Exception {

    mFont = FontFactory.create(this.getFontManager(),this.getTextureManager(), 256, 256,Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32);
            mFont.load();
}

@Override
public void onCreateScene(OnCreateSceneCallback arg0) throws Exception {

    mEngine.registerUpdateHandler(new FPSLogger());
    mCurrentScene = new Scene();
    Log.v("Scene","enter");
            mCurrentScene.setBackground(new Background(0.09804f, 0.7274f, 0.8f));
 //             return mCurrentScene;

}

@Override
public void onPopulateScene(Scene arg0, OnPopulateSceneCallback arg1)
        throws Exception {
    // TODO Auto-generated method stub

}

 }

I got code on sites there is returning scene but in AndEngine GLES2 in method onCreateScene() there is no return scene ... so my First run is BLACK .. any suggestion  :)


texts: How to devise an algorithm for a person being on a walk?

texts:
The game is an isometric RPG. The map is tile based.

I'm creating a town for this game. And I want one of the characters to roam the town randomly, because she is on a walk with her children.

I tagged the tiles she can go on. And I created a simplistic algorithm that I, in my naiveness, thought would be enough. Here it is:

If the character is blocked out and can't move in any direction she waits 1s before checking this again. If she can move in only one of the 4 directions, she moves that direction. If there is more than one possibility: If she can go forward, she always has 50% chance of going forward; if she can go both to her left and to her right there is an equal chance she chooses either of those two directions; and finally, if she can turn back, that chance is 2x smaller than turning to her left and 2x smaller than turning to her right. So, if she can choose from all 4 directions, she will have 50% chance to go forward, 20% chance to go to her left, 20% chance to go to her right, and 10% chance to go back. Repeat the above every step.

This algorithm fails beautifully. The character mostly moves randomly in one place. If she gets on a square she almost can't leave it.

I thought the solution would be to increase the chance of her moving forward. So I made the chance to go forward 5 times bigger than doing anything else. But this proved to hardly improve things.

COuld you give me some hints, point me to the correct direction? Or at least tell me that this is not worth it and I should instead resort to giving her a predefined path? (Are there no algorithms to make a character roam a given set of walkable tiles?)


texts: RPG combat and gold/exp reward equations

texts:
I have a game that I'm creating, but I'm running across issues in keeping the ratios between high and low level players similar in the battle and reward equations. Obviously a higher level player should receive less experience, but have the upper-hand in battle when fighting lower level players and monsters. Here is how I'm calculating things currently:

Battle starts If player.dex > enemy.dex Accuracy = ((player.dex - enemy.dex)/2)*20

If player.dex < enemy.dex Accuracy = ((enemy.dex*player.dex)-enemy.dex)/player.dex

Accuracy is a percentage tested against a roll of a 100 sided die.

If accuracy > roll Hit success

If accuracy < roll Hit fails

If hit success All of the attacker's damaging items (spiked helms and shields, weapons, etc.) are added together and applied as such: Damage = (player.str + item.damage)-(enemy.dex + enemy.armor)

If the player is fighting a monster, I have a base amount of gold and experience which is modified according to the player: Gold gained = (enemy.gold*rand(1,10))/player.level Exp gained = (enemy.exp*rand(1,3))/player.level

If the player is fighting another player, then there will have to be a different equation for the rewards, but I'm not sure how to go about creating that one.

As this is my first attempt at creating (though I'm an avid RPGer), I'm not sure if there is kind of an "industry standard" form of calculating these things or not. I'm also afraid that these equations won't hold up once the player reaches higher levels (say level 50+).


texts: Static spawning locations for players, creatures, items in Tiled map editor

texts:
I am using Tiled map editor. I am trying to add static spawning locations (x,y) for various entities (lets say 15) in my game. The best idea I had so far is something like this:

I am using a polygon collider named Player to declare the spawn location of the player. The width and height of this box is irrelevant. I have placed all "spawning colliders" in the same layer. I am using the Name tag to identify the type of the object.

This works fine, however, inside the editor, I would like to be able to see the type of entity (Player, monster, item, etc.) without having to select the polygon collider and look at the Name tag each time.

If I continue doing this I am going to end up with 100 grey boxes one next to the other. Is there any way of adding an indication on the collider that would represent its type (Player, monster, item, etc.) ?


texts: Directional light shader not behaving as expected

texts:
I coded my first glsl shader which manage diffuse and specular effects of a directional light.
This is the fragment shader.
#version 120

//matrix
uniform mat4 model_matrix;

//directional light position in world coordinates
uniform vec3 light_position;
uniform vec3 eye;

//send to fragment shader
varying vec4 color;
varying vec4 normal;
varying vec4 vertex;

void main()
{

    float light_diffuse_intensity;
    float light_specular_intensity;
    float light_mod;

    vec3 world_normal;
    vec3 world_vertex;
    vec3 world_reflec;
    vec3 vertex_to_light;
    vec3 vertex_to_eye;

    world_normal = (model_matrix * normal).xyz;
    world_vertex = (model_matrix * vertex).xyz;

    vertex_to_light = light_position - world_vertex; //vector from vertex to light
    vertex_to_eye = eye - world_vertex; //vector from vertex to eye
    world_reflec = 2 * dot(vertex_to_light, normalize(world_normal.xyz)) * normalize(world_normal) - vertex_to_light; //reflection of vertex_to_light

    light_diffuse_intensity = dot(normalize(vertex_to_light), normalize(world_normal.xyz)); //computing angle between light and normal
    light_specular_intensity = dot(normalize(vertex_to_eye), normalize(world_reflec)); //computing angle between eye and reflection

    if (light_diffuse_intensity > 0){
        light_mod = light_diffuse_intensity;
        light_specular_intensity = pow(light_specular_intensity, 8.0);
    }
    else{
        light_specular_intensity = 0;
    }

    gl_FragColor = vec4(mix(color.rgb * light_diffuse_intensity, vec3(1.0,1.0,1.0), light_specular_intensity), 1.0);

}

As you can see from the screenshot below, in the first screen, where I look at the sphere from the direction of the light, the border of the sphere is white because of the specular effect. However if the shader were correct it should not look like that. It should be white only in the middle of the sphere.
In the second screen, I look at both the sphere and the source of the directional light (the yellow sun) and everything looks just fine.
I cannot find the error in my shader, could someone help please?
Thank you very much!


texts: How do I simulate a crowd in the stadium stands?

texts:
I'm working on a mobile sports game with Unity. I'm wondering how I could create an efficient effect of an audience in the stadium.

I know that with more than 15 characters in my games (with 1800 faces and 20 bones) the game slows down, so I guess that even with a small number of bones, using 3D characters for even the first row of seats isn't feasible... Would you have some tips on how to do this another way?

I have also tried to "paint" them, and add a blur effect, but the result is not very good...


texts: Creating Dynamic Weapons in Unreal Engine?

texts:
Back Story: Learning Unreal Engine 4 from scratch, I am making a fantasy Darksouls-ish Game.

I am Having trouble understanding Creating a weapon and allowing the character to hold it with added Functions.
For example, I want to have a working torch, lights, flame, stick, to appear in his hand at the press of a button.

I do not know if I am going about this in the correct way, but this is what I did:

Created a Static Mesh (Torch Stick)
Added The Flame and Light Source to it (Emitter & Point Light)
Put the Emitter and Point Light into the Torch Tree
Created a Socket in "Persona" in the left hand

At this point I got stuck, because the third person Blueprint. Doesn't Register my amateur Torch as an "Asset".

I watched some "Equipping Weapon tutorials" But the problem is they don't explain where their weapons came from Ex (Rifle), or if they are dynamic  (Lights or laser sights)

How am I supposed to go about this? Thanks


texts:
What is the preferred methods for doing so, performance-wise?

For example I want to pick certain objects in an area around a given point.

What I have thought off so far is using invisible objects as extended hit detectors. Like creating a circle or square then have collision responses to them.

Or maybe just pass the entire object list and iterate on it, then using a distance/angle based condition.


texts: Animating MultiPart 2D Character with RigidBodies

texts:
Some background to the question:
I am attempting to animate and control a large multi sprite 2D Boss character for a platforming game.
Up until this point I had been assigning individual animators for each of the limbs and using RigidBody2D to control the movement of each one respectively.
This worked fine except for one thing: synchronizing each animation state with the other controllers was a huge pain in the ass and error prone.

Hence my next step was creating one single Animation Controller using multiple layers to manage the animations together. This worked great, on the animation side of things. Catch was that now it had become completely impossible to alter the Transform of the the individual limbs (any child component below the animator)

 - Boss Character (main scripts and animator)
   -- BossHead (collider)
       -- SpriteHolder
   -- BossTorso (collider)
       -- SpriteHolder
   -- BossLeftHand (collider)
       -- SpriteHolder
   -- BossRightHand (collider)
       -- SpriteHolder

I have tried using
transform.Translate instead of a
RigidBody2D (same result)
I have
tried checking apply root motion in
the animator (same result)
I have
doubly checked that no transform
values were being modified during the
animation (same result)

Unity version 2018.2.11
This use case does not seem to be all that unusual so there must be a correct workflow for this.
Question is, what is the Unity correct way to achieve this?
EDIT: Code That updates the RigidBody2D
Void LateUpdate() {
    if (_path == null)
        return;

    if (_currentWaypoint >= _path.vectorPath.Count)
    {
        if (!_reachedEndOfPath)
        {
            _reachedEndOfPath = true;
            _rb.velocity = Vector2.zero;
            _callback?.Invoke();
        }
        return;
    }
    else
    {
        _reachedEndOfPath = false;
    }

    Vector2 direction = ((Vector2)_path.vectorPath[_currentWaypoint] - _rb.position).normalized;
    Vector2 force = direction * speed * Time.deltaTime;
    _rb.AddForce(force);

    float distance = Vector2.Distance(_rb.position, _path.vectorPath[_currentWaypoint]);
    if (distance <= _nextWaypointDistanceMargin)
        _currentWaypoint++;
}

Example of the effect I am attempting to create:

Main boss with two disembodied hands that can float around to chase the player.


texts: Graph search with a high number of actions

texts:
I have implemented A* to reach a goal state from a start state. My state is position X,Y, angle and others state variable. I have a number of actions.
What I call actions is : A* on a grid has 4/8 actions (straight, right, left, back).

My character has a lot of different actions. I started with 20 possible actions which will lead to different future possible positions. with my implementation of A* it is working fine and I found a solution.

Now, I want to do the same thing but with my real number of actions. Which is around 1000... If I run my algorithm it may take forever...

This figure shows my problem :

The first red node is the start position.
The green is the goal.
When A* will expand my children. I will have 1000 children nodes (note: the nodes are in a kind of same region the light blue envelope)). But then I have 1000 nodes to study and which can be extented by 1000 children each... and so on. So the number can be really huge.

Does anybody have a good idea to deal with this kind of high number of actions in a A* ? Finding a good heuristic won't be enough I guess cause too many possibilities. Maybe using this light region ?
Any ideas ?

Thanks.
Let me know, If it is unclear or need more explanations.


texts:
So, I'm currently working on a game.
The objects are treated as prefabs, so every time it is instantiated, the position of the object must randomize.
public ObjectDisplay SpawnObject()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.5f, 2.5f), 7f);

    GameObject obj = Instantiate(objPrefab, randomPosition, Quaternion.identity, objCanvas);
    ObjectDisplay objDisplay = obj.GetComponent<ObjectDisplay>();

    return objDisplay;
}

The randomPosition is what is supposed to be changing the positions, but what happens is that the prefabs would continue to spawn from the middle of the screen. I've tried changing the position values but that didn't do much.
The code is seemingly fine, but it doesn't function the way it is supposed to. Any ideas?


texts: Why does GameComponent have an Initialize() method?

texts:
I'm not sure if this exact question has been asked before, but all I could find were questions about how to work with GameComponent, or why something wasn't working.

I understand that you overload the Initialize, Draw, and Update methods with your own code, and XNA will then invoke them when the time is right. But what exactly is the purpose of Initialize? If you're writing something that extends from GameComponent, why wouldn't you just put all your initialize logic in the constructor?

For example, if my classes have a reference type that needs to be initialized, such as a collection or dictionary, I make of point of doing so in the constructor, and this pattern follows me into my GameComponent class design.

EDIT: Having worked with it a bit more, it looks like the primary purpose is to allow for more flexibility.

For example, IGameComponent merely exposes one method -- Initialize() -- and by implementing this, you are allowed to plug it into the Game.Components collection. This means that GameComponent, with all of its various properties, even the reference to Game, is just an implementation detail.

Another use I've found is when one component contains a collection of other components. In this case, the constructor for the container is called, and you now have empty collections. This pattern allows you to populate the collections, then call the initialize on both the parent and children objects.

I'm still stumped as to what I would specifically put into Initialize, but I understand the reasoning behind it.


texts: I would need an idea on how to animate a player in a board game that is top-down and 2D?

texts:
I'm planing a 2D board game and I cannot figure out how to make the animation of the player from tile to tile. Note that tiles are not in a grid, they are flexible (x, y) points in the map.

The ways I found until now:

Just move the player from (xi, yi) to (xf, yf) with nothing special
An helicopter comes from an edge an transport the player (a circle) to the next tile
A little man walking by making it in a wrong perspective (side)

Do you have any better ideas, thanks alot?


texts: Reading depth buffer result in only two values

texts:
I am attempting to add an SSAO post processing shader to my deferred rendering engine. I am running into problems with reading from the depth buffer. In the images linked below you can see the depth buffer, and the values I'm reading out of it (the values are scaled - see 'range' value at top of image)

Depth Buffer

What I read from the depth buffer

It looks to me like the format must be wrong somehow but I'm not sure in what way.

The depth buffer is being created as follows:

// Texture
D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory(&textureDesc, sizeof(textureDesc));
textureDesc.Width = m_Desc.Width;
textureDesc.Height = m_Desc.Height;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
textureDesc.MiscFlags = 0;
HRESULT hr = m_pDevice->CreateTexture2D(&textureDesc, nullptr, &m_pDepth);

// DS VIEW
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
ZeroMemory(&descDSV, sizeof(descDSV));
descDSV.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
hr = m_pDevice->CreateDepthStencilView(m_pDepth, &descDSV, &m_pDepthStencilView);

// SR View
D3D11_SHADER_RESOURCE_VIEW_DESC depthSrvDesc;
ZeroMemory(&depthSrvDesc, sizeof(depthSrvDesc));
depthSrvDesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
depthSrvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
depthSrvDesc.Texture2D.MipLevels = 1;
depthSrvDesc.Texture2D.MostDetailedMip = 0;
hr = m_pDevice->CreateShaderResourceView(m_pDepth, &depthSrvDesc, &m_pDepthShaderResourceView);

And the important parts of my SSAO shader:

Texture2D gTextureDepth;

struct VS_INPUT
{
    float3 Position : POSITION;
    float2 TexCoord : TEXCOORD0;
};

struct PS_INPUT
{
    float4 Position : SV_POSITION;
    float2 TexCoord : TEXCOORD0;
};

PS_INPUT VS(VS_INPUT input)
{
    PS_INPUT output = (PS_INPUT)0;

    output.Position = float4(input.Position, 1.0f);
    output.TexCoord = input.TexCoord;

    return output;
}

float4 PS(PS_INPUT input) : SV_Target
{
    int3 loadCoord = int3(input.Position.xy, 0);

    float depth = gTextureDepth.Load(loadCoord).r;

    return float4(depth, depth, depth, 1.0);
}

Any ideas?


texts:
I'm writing a game engine in C++ with Irrlicht and Bullet Physics. All of my Irrlicht code works perfectly, but upon creating Bullet Physics objects with new, and later freeing them, my program throws a free(): invalid pointer error.

Backtracing with gdb shows that the error is a libc raise() when Irrlicht tries to delete an Octree I am using for the game map: irr::scene::COctreeSceneNode::deleteTree().

The full gdb backtrace is:

free(): invalid pointer

Program received signal SIGABRT, Aborted.
0x00007ffff7455f25 in raise () from /usr/lib/libc.so.6
(gdb) bt
#0  0x00007ffff7455f25 in raise () from /usr/lib/libc.so.6
#1  0x00007ffff743f897 in abort () from /usr/lib/libc.so.6
#2  0x00007ffff7499258 in __libc_message () from /usr/lib/libc.so.6
#3  0x00007ffff74a077a in malloc_printerr () from /usr/lib/libc.so.6
#4  0x00007ffff74a214c in _int_free () from /usr/lib/libc.so.6
#5  0x00007ffff7bd3b69 in irr::scene::COctreeSceneNode::deleteTree() ()
   from /usr/lib/libIrrlicht.so.1.8
#6  0x00007ffff7bd41ae in irr::scene::COctreeSceneNode::~COctreeSceneNode() ()
   from /usr/lib/libIrrlicht.so.1.8
#7  0x00007ffff7bd4474 in virtual thunk to irr::scene::COctreeSceneNode::~COctreeSceneNode() () from /usr/lib/libIrrlicht.so.1.8
#8  0x00007ffff7bf2706 in irr::scene::CSceneManager::removeAll() ()
   from /usr/lib/libIrrlicht.so.1.8
#9  0x00007ffff7bf971e in irr::scene::CSceneManager::~CSceneManager() ()
   from /usr/lib/libIrrlicht.so.1.8
#10 0x00007ffff7bf9c54 in virtual thunk to irr::scene::CSceneManager::~CSceneManager() () from /usr/lib/libIrrlicht.so.1.8
#11 0x00007ffff7d45e5e in irr::CIrrDeviceLinux::~CIrrDeviceLinux() ()
   from /usr/lib/libIrrlicht.so.1.8
#12 0x00007ffff7d45f54 in virtual thunk to irr::CIrrDeviceLinux::~CIrrDeviceLinux() () from /usr/lib/libIrrlicht.so.1.8
#13 0x000055555556b97e in irr::IReferenceCounted::drop() const ()
#14 0x000055555556a88f in IrrlichtHandler::drop_device() ()

The code which seems to be the cause of the error is the initialization:

    /* PHYSICS SETUP*/
    btDefaultCollisionConfiguration *col_config = new btDefaultCollisionConfiguration();
    btCollisionDispatcher *dispatcher = new btCollisionDispatcher(col_config);
    btBroadphaseInterface *overlapping_pair_cache = new btDbvtBroadphase();
    btSequentialImpulseConstraintSolver *solver = new btSequentialImpulseConstraintSolver;
    btDiscreteDynamicsWorld *dynamics_world = new btDiscreteDynamicsWorld(
        dispatcher, overlapping_pair_cache, solver, col_config
    );

    dynamics_world->setGravity(btVector3(0,-10,0));

and deletion of Bullet:

irrlicht_handler.drop_device();

    for(int i=dynamics_world->getNumCollisionObjects()-1; i>=0; i--)
    {
        btCollisionObject *obj = dynamics_world->getCollisionObjectArray()[i];
        btRigidBody *rb = btRigidBody::upcast(obj);
        if(rb && rb->getMotionState())
        {
            delete rb->getMotionState();
        }
        dynamics_world->removeCollisionObject(obj);
        delete obj;
    }

    delete dynamics_world;
    delete solver;
    delete overlapping_pair_cache;
    delete dispatcher;
    delete col_config;

The full code is on Github.


texts:
I was following this tutorial, but the lightning is not hitting the other object as the video shows.

    private LineRenderer lRend;
private Vector3[] points = new Vector3[5];

private readonly int point_Begin = 0;
private readonly int point_Middle_Left = 1;
private readonly int point_Center = 2;
private readonly int point_Middle_Right = 3;
private readonly int point_End = 4;

public Transform line;

private readonly float randomPosOffset = 0.3f;
private readonly float randomWithOffsetMax = 2f;
private readonly float randomWithOffsetMin = 1f;

private readonly WaitForSeconds customFrame = new WaitForSeconds(0.05f);

void Start () {
    lRend = GetComponent<LineRenderer>();
    StartCoroutine(Beam());
}

private IEnumerator Beam()
{
    yield return customFrame;
    points[point_Begin] = transform.position;
    points[point_End] = line.position;
    CalculateMiddle();
    lRend.SetPositions(points);
    lRend.SetWidth(RandomWidthOffset(), RandomWidthOffset());
    StartCoroutine(Beam());
}

private float RandomWidthOffset()
{
    return Random.Range(randomWithOffsetMin, randomWithOffsetMax);
}

private void CalculateMiddle()
{
    Vector3 center = GetMiddleWithRandomness(transform.position, line.position);

    points[point_Center] = center;
    points[point_Middle_Left] = GetMiddleWithRandomness(transform.position, center);
    points[point_Middle_Right] = GetMiddleWithRandomness(center, line.position);
}

private Vector3 GetMiddleWithRandomness (Vector3 point1, Vector3 point2)
{
    float x = (point1.x + point2.x) / point_Center;
    float finalX = Random.Range(x - randomPosOffset, x + randomPosOffset);
    float y = (point1.y + point2.y) / point_Center;
    float finalY = Random.Range(y - randomPosOffset, y + randomPosOffset);

    return new Vector3(finalX, finalY, 0);
}
}

Everything is good except that the lightning is not hitting the other object. What am I missing?


texts: Change emission level of a set of vertices within a mesh

texts:
ok so here is the problem I need to solve.

I have a known set of vertices that I need to "animate" the emission level of. Currently I have a vertex definition setup and RGB color data for each vertex. and I can animate that. but obviously that doesn't effect the lighting.

what would be ideal I think is if I could take the basic effect class and apply it to just a few vertices at a time but so far I cant find a way to use it on anything less than a mesh.

Update

Thanks to Evan I think the way to go is to get each of these indices and create a mesh that will overlay the existing model. This would make it easier to control transparency as well as the emission.

The question I have is lets say these indices do not make up a full triangle? Maybe after I find all of the vertices I also find that they don't divide out to 3.

I guess what I need now is what would a good way to pull this mesh apart be?


texts: Generating spherical world from heightmapped terrain

texts:
I am using a standard heightmapped procedural terrain in my project.  However, I want the terrain to appear spherical when the user zooms out.  This is an attempt to simulate the appearance of a spherical planet.  Here is my current algorithm:

        //get the direction from the "planet" center to this vert
        Vector3 sphereCentertoVertPosition = vert.Position - SphereCenter;
        sphereCentertoVertPosition.Normalize();

        //our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center
        RotationAxis = Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition);

        //the amount we rotate is based on the distance of this vert from the center of the terrain
        Vector3 fromCenter = vert.Position - Root.Position;
        float amount = (fromCenter.Length() / ((myTextureWidth / Scale) / 2)) * (float)Math.PI;

        Quaternion rot = Quaternion.CreateFromAxisAngle(RotationAxis, amount);

        Vector3.Transform(ref vert.Position, ref rot, out vert.Position);

My main concern is that the rotation axis is not correct.  Theoretically, should it be the cross between the vert-to-planet-center and the terrain-center-to-planet-center?


texts: Will changing the scale of objects in Unity have adverse effects?

texts:
Relative to what they are by default, I mean. For example compared to the character controllers that come with Unity. If I make the character 4 times the size, will that cause problems, with the physics and everything? Or are there just changes in a couple values that I'd need to make?

Does Unity expect that 1 unit will always be around 1 meter?


texts:
I have a tile based isometric map and an A* algorithm that returns a path. I am looking to smooth this path efficiently but with good aesthetics. Basically i am using my grid for building the map and pathfinding but i want the player, enemies and certain types of objects to be detached from this grid.

I can think of a line of sight implementation where i start at the first tile of the path, from there check each further tile if i have a clear path straight to it. And repeat from there.


texts:
I have a Player game object with a sprite renderer and a line renderer.
The sprite for its body and the line for a rope.
The problem is that the rope isn't visible (I can see it's drawn in the scene but not in-game).
I can also see the rope if I disable the background.

I have the following sorting layers (in this order):

Background
Platforms
Default

I have tried multiple combinations of sorting layers and other ordering attributes but none worked. The current one is:

Sprite Renderer is in the Default sorting layer with an order in layer of 1
Line Renderer is also in the Default sorting layer with an order in layer of 0
The background game object has a Tilemap Renderer in the Background sorting layer with an order in layer of 0

This combo worked with no background, but, with it, the line is gone. The values of order in layer were tweaked (before the background) in such a way that the line would be drawn behind the sprite and that worked.

The line positions all have a z value of 0. If I change it to a negative value (say, -0.1f) the line gets drawn on top of everything (even the sprite, which I don't want). I could probably offset the player position in the z axis, but that could mess up some calculations.

Thanks in advance to anyone who's willing to help!


texts: Time passing display on UI in Unity in C#

texts:
How can I display the time and how many days on a UI in Unity. Time would be moving faster like a week in 7 minutes?

Should I use Time.deltaTime and how do I excellerate the time it displays?


texts: How do i play mp3 files in Unity Standalone?

texts:
I am making a game in Unity in which the player can select music files in their hard drive to use them in-game. I use the WWW class to load the sound files, but this only works for OGG, WAV and Tracker files. I use the following code:

WWW www = new WWW ("file:///" + soundPath);
while(!www.isDone){
    yield return 0;
}
GetComponent<AudioSource> ().clip = www.GetAudioClip(false, true);

I want to play audio files in mp3 format, which is the most widely used format for music in general, but when i try to play them, this gets printed to the debug log:

  Streaming of 'mp3' is not supported on this platform.

How can i easily achieve mp3 playback on desktop?


texts: Why does my Point light turn off if Player walks in any direction in Unity 2D?

texts:
My 2D Sprite has a material, Sprite diffuse attached to it.

Now when I set up a light, it works but if I play the Game and walk, the light turns off immediately and the Player turns black.

The light is set up, Type as Point and Baking as Realtime, Distance at Z-axis is -25.

The Camera distance is at -30 on the Z-axis.

The Player is at 0 on the Z-axis.

I set the light between Camera and Player, but I also have a Camera Follows Player script, maybe it causes the problem, but I watched the Z-axis while playing and it doesn't move on the Z-axis.

I will also post Camera Script if someone can detect any problem.

{
    private Vector2 velocity;

  public float smoothTimeY;
  public float smoothTimeX;

  public GameObject player;

  // Use this for initialization
  void Start ()
  {
    player = GameObject.FindGameObjectWithTag("Player");
  }

  // Update is called once per frame
  void FixedUpdate ()
  {
    float posX = Mathf.SmoothDamp (transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX);
    float posY = Mathf.SmoothDamp (transform.position.y, player.transform.position.y, ref velocity.y, smoothTimeX);

    transform.position = new Vector3 (posX, posY + 29, transform.position.z);
  }
}


texts:
In my game you collect coins (surprise!). At the moment I generate them like this:

Find a random position given a rectangle (eg. the screen size) and generate a coin
Possible positions are left and right of this coin for our next coin

If both are available, choose at random
If a coin exists in one position, use the other
If neither are available skip this step

Do the same for up and down positions of the new coin
Repeat this sequence for all available coins

This works fine but I would like to create custom shapes with my coins like arrows, stars etc. This got me thinking into how I could achieve this. One way I thought of was to use a small texture where each coloured pixel represented the position of a coin. So that a picture like this:

Can be used to generate an array of coin position coordinates in any framework supporting textures. I'm pretty sure this can be done, but was wondering if anyone has tried this or something totally different for generating coins or any other objects in a game. Ideally the game would involve several different textures and choose them at random, and combine this with the random scattering textures from simple algorithms such as the one I have above.


texts: Portal View/Projection Matrix near plane

texts:
For RenderToTexture/Camera based portal rendering, the basics seems simple enough.

However, with a free camera, most of the time it is going to be looking at such portals at an angle:

Now a regular near clipping plane will not always work here, it will either intersect with the wall the portal is sitting on, or possibly with objects in front of the wall.

The desired near clipping plane would be aligned like the portal, producing a view volume more like this:

or this in 3D:

So here is my question:

How does one construct or "truncate" a view/projection matrix to achieve such an off-camera-normal (near) clipping plane?


texts: Competing with C++ for games programming

texts:
I'm curious as to why C++ is so popular for games development, and not other languages instead. I know you can create very fast code with it, but what exactly is it that makes it popular?

Is it just because it's fast?
Is it some other feature in the language, like the OO paradigm or the portability?
Is it because of all the libraries that have been created over time?
Or some combination of all these (and other) reasons?

If someone could fill me in on this, I'd be very happy. :-)


texts: How to change object curve path in playmode in Unity?

texts:
I would like to make some sort of this simulation below, where user can interact with the white rod and drag it into the magnetic fields, which in resulting the blue line that represent the magnetic field of the permanent magnet to move in semi-circular motion.

I managed to get that kind of effect using animation

I wish I do not have to make an animation for it by manipulation path for the sphere to be automatically correcting it's own path after colliding with the round object since the sphere will suddenly moving faster than usual when colliding with much bigger round object.

I have tried using splines etc, but most tutorial I've seen are not editable in play mode, which is I cannot alter any of the curve values inside my script. So can anyone could provide me some insight or another better alternative than this? I've been stuck here for three days now.

Thanks!

EDIT:


texts: Get BP FollowCamera Rotation and Location

texts:
I'm accessing my FollowCamera https://imgur.com/a/vbFagxg from my BluePrintCharacter class in my C++ code, with this following line :

FollowCamera = GetOwner()->FindComponentByClass<UCameraComponent>();
FVector WorldLocationV = FollowCamera->GetWorldLocation();

But when I run my game, I get this error : GetWorldLocation is not a member of UCameraComponent

Why is this, and how can I get GetWorldLocation from FollowCamera in C++?

In BluePrint this seems to work fine : http://i.imgur.com/8m9TWUW.png


texts: How do engines that can be scripted with a different language than the engine code work?

texts: There are some engines that can be scripted with different languages than that of which the engine, itself, is written with. How does that work?


texts: How do I know if a perspective matrix is right or left handed coordinate system?

texts:
For example, if I define my perspective matrix as the following:

m[0]  = 1.f / ( aspect * focalLength );
m[5]  = 1.f / focalLength;
m[10] = -zFar / (zFar - zNear);
m[11] = -1;
m[14] = -(zFar*zNear)/(zFar - zNear);

How can I tell if my perspective matrix is right or left handed coordinate system?


texts: What is the best way to implement the story functionality (dialogue and cutscene management, etc.) in an RPG?

texts:
I would like to know what the best way to implement the story functionality of an RPG would be. I am writing the game in C++ using the SFML library for graphics, and I have implemented drawing tiles, level loading and player movement, but I am not sure on how exactly to go about implementing the story. How would I implement when to do cutscenes, what to do in cutscenes, changes in dialogue, and have dialogue options affect the game? I am planning to have the dialogue in JSON files in a format similar to this

"dialogue" :[
        {"type" : "dialogue", "character" : "player", "text" : "dialogue here", "result" : "next"},
        {"type" : "dialogue", "character" : "character", "text" : "more dialogue", "result" : "next"},
        {"type" : "option", "options" : [{"text" : "option 1", "result" : "goto 4"}, {"text" : "option2", "result" : "goto 5"}]},
        {"type" : "dialogue", "character" : "character", "text" : "from option 1", "result" : "next"},
        {"type" : "dialogue", "character" : "character", "text" : "from option 2", "result" : "next"}
]

Is this a good way to go about this?
Should I also consider embedding a scripting language like Lua for cutscenes and other high-level tasks?


texts: looking for a system for writing branching dialog

texts:
I'm creating an HTML5 RPG and need to write NPC dialog. In my beta, I wrote the dialog in spreadsheets and assigned lines to NPC by ID. Branching required writing a complicated flag system. It was impossible for anyone to read through it and understand what was going on.

I'm looking for a better alternative to writing branching story dialog. The dialog will require some degree of in-text markdown support (so I can be sure which text to highlight with CSS). In the spreadsheet, that looked like

  "Hello, my name is [name: John]. Welcome to [location: Aragon]. Please fetch the [keyword: sword]"

Would would appear as:

  "Hello, my name is John. Welcome to Aragon. Please fetch the sword"

These would be higlighted/handled differently in code.


texts: How do i easily clamp my cameras rotation when using transform.rotate()

texts:
I'm making a fps controller, and I'm trying to clamp my cameras x rotation.  Here's my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] Camera cam;
    [SerializeField] float camSpeed;
    [SerializeField] float walkSpeed;
    [SerializeField] float jumpSpeed;

    float yaw;
    float camPitch;
    Vector3 direction;
    Vector3 worldDirection;

    Rigidbody myrigbody;
    void Start()
    {
        myrigbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        camPitch = -Input.GetAxis("Mouse Y") * camSpeed;
        cam.transform.Rotate(new Vector3(camPitch, 0, 0));
        yaw = (yaw + Input.GetAxis("Mouse X") * camSpeed) % 360f;

        direction = new Vector3(Input.GetAxis("Horizontal") * walkSpeed, myrigbody.velocity.y, Input.GetAxis("Vertical") * walkSpeed);
        worldDirection = transform.TransformVector(direction);

        if(Input.GetKeyDown(KeyCode.Space))
        {
            myrigbody.AddForce(new Vector3(0, jumpSpeed, 0), ForceMode.Impulse);
        }
    }
    private void FixedUpdate()
    {
        myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0));
        myrigbody.velocity = worldDirection;
    }
}

I know that I want to clamp my cameras X rotation within a range of -89 to 89, but no matter what I try I can't figure out how to clamp the rotation while using cam.transform.Rotate(). I don't think I can clamp camPitch, because it is reset every frame, and I can't figure out a way to directly clamp the cameras rotation.  The cameras rotation is not resetting, so if I could somehow clamp it it would work.  Is this possible, or do I need to try a different method?  How do i get this to clamp correctly?