texts: Why the transform.localPosition never equal to the begin position of the transform?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveScrollView : MonoBehaviour
{
    float seconds;
    Vector3 begin;
    Vector3 end;
    Vector3 difference;

    public static bool go = false;
    public static bool goBack = false;
    public static bool atOriginPos = false;

    void Start()
    {
        seconds = 0.5f;

        begin = transform.localPosition;
        end = new Vector3(0, -1, 0);
        difference = end - begin;
    }

    void Update()
    {
        if (go)
        {
            if (transform.localPosition.x < end.x)
            {
                var mx = transform.localPosition.x;
                transform.localPosition = new Vector3(mx += seconds * Time.unscaledTime, -1, 0);
                difference = end + transform.localPosition;
            }
        }

        if(goBack)
        {
            if (transform.localPosition.x > begin.x)
            {
                var mx = transform.localPosition.x;
                transform.localPosition = new Vector3(mx -= seconds * Time.unscaledTime, -1, 0);
                difference = end - transform.localPosition;
            }
        }

        if(transform.localPosition == begin && goBack)
        {
            atOriginPos = true;
        }
    }
}

At the Start the begin position is (-540.0, -1.0, 0.0) also the transform.localPosition is at the same position.
Then at this line 39 :
if (transform.localPosition.x > begin.x)

The value of the x of the transform.localPosition is 3.039021 and the x of the begin is -540
So it's getting inside and move the transform.
Then when the transform has finished moving I see on this line :
if (transform.localPosition.x > begin.x)

The transform.localPosition x value is -540.7267 and the x value of the begin is still -540
So now it will not get inside and will not move the transform anymore.
But two wrong things happened :

The transform stopped moving but it didn't move to it's original position only close to it.

Because it didn't move to it's exact original position then the localPosition x and the begin x are never equal so the this will never be true :
if(transform.localPosition == begin && goBack)

And the flag atOriginPos is never true.
I want the transform to move back to it's original position and then when it's reached the original position set the flag atOriginPos to true.


texts: Implementation of a quaternion based hinge constraint

texts:
I'm trying to implement a hinge joint between two rigid bodies based on Lagnange multipliers, s.t. constraint functions to be constraints on quaternions, which describe bodies orientation, itself. It's more natural than describe constraints in terms of some vectors rigidly connected with bodies as it is just implicit quaternions. Plus quaternions should handle the problem of bistability of "vectorial constraints". It is essential to write the correct constraint functions.

It seems that I found the correct constraints but something goes wrong (later). Tell me, please, if I do something wrong or miss something. Let us concentrate just on unlimited hinge rotation of two rigid bodies about some common axis. So we need to get rid of two degrees of freedom. Let

q = rAconj qAconj qB rB,

where qA and qB are usual orientation quaternions (s.t. if a vector V has a coordinates column V' in a frame of a body B (lets name this frame B') then (qB*(0, V')*qBconj).im is its coordinates column in a world frame (lets call this frame W)), rB is a quaternion which carry out rotation from frame where the axis, bodies rotate about, direction vector has coordinates (0, 0, 1) (lets call this frame B'') to frame B', rA defined by analogy.

The hinge constraint would not be violated iff vectorial part of q is collinear with Z axis. I.e. the (coordinate) constraints are just

q.x = 0,
q.y = 0.

Then differentiating this equations, minding Leibniz rule, unitarity of quaternions and dq/dt = 0.5 q (0, w) identity we get

qdot = 0.5 rAconj (qAconj qB (0, wB) - (0, wA) qAconj qB) rB

and the velocity constraints:

qdot.x = 0,
qdot.y = 0.

Velocities are "decoupled" so to get Jacobian is a matter of simple quaternion multiplication. For convenience while experimenting I just write short functions getC, getCdot by which Jacobian is calculated. I'm quite sure in that part of code 'cause I've tested with "not quaternion version" of getCdot and it works fine.

Everything works fine if one of the bodies has an infinite inertia (kinematic body) or (if both bodies are dynamic) if angular velocities are orthogonal or collinear to rotation axis. If angular velocities are in general case simulation blows up. Can you get a tip why is this happening? This is not because of quadratic term (Coriolis', gyroscopic, ...) in the Euler equations -- I ignore this term for now for the sake of stability.


texts: Adding multiple game objects into a prefab

texts:
Is it possible for one prefab to contain multiple game objects, preferably in a parent-child relation. I am making a complex enemy that I want to separate into a couple of game objects with separate sprite renderers, scripts and other parameters. This would simplify the code I need to write for each of the elements. I know I can create one (the parent) object, and then instantiate the others in the Awake() or Start() methods, but I'm asking if there is a way to create a prefab that would contain all of the necessary elements (so I can create the entire thing with one Instantiate() call.

Thanks


texts: Most effective approach when creating % chance of something

texts:
When dealing with % chance in a game what are the most effective ways to achieve this? When I use random.random()[python] or Math.random()[javascript] and use an if/elif/else conditional it seems like the things with a very low chance of happening, happened far more often than they should have.

For example, a python game I worked on used something like this:

qaul_eq = random.random()
if qual_eq <= .5:
   quality = common
elif qual_eq <= .75:
   quality = uncommon
elif qual_eq <=.9:
   quality = rare
elif qual_eq <=.97:
   quality = epic
else:
   quality = legendary

Javascript DEMO

There is a 2% chance that quality will be legendary yet when printed 20 times every time it is run at least 1 item in almost every test run is legendary. In my python game it isn't uncommon for 2 or 3 of the items to be legendary. I'd chalk it up to good luck if not for the large amount of test runs I have conducted.


texts:
I managed to make my 3D player character jump (hurrah!) but I get an unwanted jump upon landing.
It's not a mid-air double-jump. If I press space mid air, then after it get backs to ground it immediately jumps again.
How can I prevent this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    bool jumpKeyIsPressed;
    float horizontalMovement;
    bool isGrounded ;
    Rigidbody rb;
    [SerializeField] float playerJumpForce;
    [SerializeField] float movementSpeed;

    void Start()
    {   //sustituye GetComponent<Rigidbody>() por rb!!!
         rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyIsPressed = true;
        }

        horizontalMovement = Input.GetAxis("Horizontal");
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector3(horizontalMovement * movementSpeed, rb.velocity.y, 0);

        if (jumpKeyIsPressed && isGrounded)
        {
            rb.AddForce(Vector3.up * playerJumpForce, ForceMode.VelocityChange);
            isGrounded = false;
            jumpKeyIsPressed = false;
        }
    }
}


texts: Null Reference Exception error occurs when trying to override AndroidManifest file in unity?

texts:
So I Created A manifest file in Assets/Plugin/Android/. The File contains:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
 <activity android:name="com.unity3d.player.UnityPlayerActivity" android:windowSoftInputMode="stateHidden"></activity>
</manifest>

Error Occurs when building:

  NullReferenceException: Object reference not set to an instance of an
  object

  UnityEditor.AndroidManifest.SetApplicationFlag (System.String name,
  Boolean value)

  UnityEditor.AndroidManifest.SetDebuggable (Boolean debuggable)

I followed the docs from here, about Overriding the Android Manifest.

The apk builds fine when the manifest is removed.

Complete Error:

  NullReferenceException: Object reference not set to an instance of an object
  UnityEditor.AndroidManifest.SetApplicationFlag (System.String name, Boolean value)
  UnityEditor.AndroidManifest.SetDebuggable (Boolean debuggable)
  UnityEditor.Android.PostProcessor.Tasks.GenerateManifest.PatchManifest (UnityEditor.Android.PostProcessor.PostProcessorContext context, System.String manifest)
  UnityEditor.Android.PostProcessor.Tasks.GenerateManifest.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
  UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
  UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report)
  UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties)
  UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:286)
  UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

UNITY 2018.3.4f1


texts: Content.Load() throws ContentLoadException when loading a texture in SL XNA

texts:
I've developed a while back in XNA but I'm a bit rusty. I've started working on SL XNA but have a problem I can't explain while trying to load content (model -fbx- or texture).

I place the image named redRect.jpg in the Content project by right-click -> Add existing item and I've made sure all the properties are ok:

Asset Name: redRect
Build Action: Compile
Content Importer: Texture - XNA Framework
Content Processor: Texture - XNA Framework

I declare a texture

Texture2D redTexture;

but when I try to load the texture

redTexture = contentManager.Load<Texture2D>("redRect");

I get an error telling me that the image is not found

  Error loading "redRect". File not found.


texts:
The initial problem I'm trying to solve is for pac-man, but of course there must be thousands of other situations with the same problem. I consider the pac-man grid to be a graph (two ways of doing this: either each grid square is a vertex, OR each "intersection" is a vertex and the "hallways" are the edges), and try to find a path that eats all the food (not worrying about ghosts for the moment).

I've noticed that certain grids can be clearly separated into sub-grids, where there is a single bottleneck that must be crossed in order to get into/out of the sub-grid. This of course translates into being able to partition the graph into two sub-graphs that share a single node and no edges.

What algorithms exist for finding these sorts of sub-graphs (that are "pinched off" from the rest of the graph by a single vertex)? I'm looking for a quick run-down of what's out there, as a starting point for further research.


texts: Invalid coordinates returned by glutMouseFunc()

texts:
I am using GLUT's glutMouseFunc() function to retrieve the coordinates of mouse clicks.  I want to move the object on that coordinate to another coordinate.  But when I click on the object the coordinates returned by glutMouseFunc() are different than the original.

windowWidth=1250;
windowHeight=1000;

void onMouse(int button, int state, int x, int y);

int main(int argc, char** argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(1250, 1000);
    glutCreateWindow("OpenGL - First window demo");
    // ...
    glutMouseFunc(onMouse);
    // ...
    glutMainLoop();
    return 0;
}

void onMouse(int button, int state, int x, int y) {
    flag++;
    if (state != GLUT_DOWN && button!=GLUT_LEFT_BUTTON)
        return;

    GLbyte color[4];
    GLfloat depth;
    GLuint index;

    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, color);
    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
    glReadPixels(x, windowHeight + y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT, &index);

    printf("Clicked on pixel %d, %d, color %02hhx%02hhx%02hhx%02hhx, depth %f, stencil index %u\n", x, y, color[0], color[1], color[2], color[3], depth, index);
    move();
}

Inside my render function i have set the window coordinates to 0,0 using glortho

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, windowWidth, windowHeight, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

If my object is at (550, 900), onMouse() reports it as (556, 650) while if I click on an object which is at position (375, 475) the onMouse() returns (376, 342).

Basically there is a huge difference between the value of y axis returned by the function.

How can i get the correct screen coordinates?


texts: Applying a noise texture to distort edges

texts:
I asked this question over on StackOverflow but then found this site, and it's probably better suited to here.

I'm trying to implement Sketchy Drawings.  I'm at the part of the process which calls for the use of the noise texture to derive uncertainty values that will provide an offset into the edge map.

Here is a picture of my edge map for a torus:

And here is the noise texture I've gotten using the Perlin function as suggested:

I have these saved as textures in edgeTexture and noiseTexture respectively.

Now I'm stuck on the section where you have to offset the texture coordinates of the edge map by uncertainty values derived from the noise texture. This image is from the book:

offs = turbulence(s, t);
offt = turbulence(1 - s, 1 - t);

I'm ignoring the 2x2 matrix for the time being.  Here is my current fragment shader attempt and the result it produces:

#version 330

out vec4 vFragColor;

uniform sampler2D edgeTexture;
uniform sampler2D noiseTexture;

smooth in vec2 vTexCoords;

float turbulence(float s, float t)
{
    float sum = 0;
    float scale = 1;
    float s1 = 1;
    vec2 coords = vec2(s,t);

    for (int i=0; i < 10; i++)
    {
        vec4 noise = texture(noiseTexture, 0.25 * s1 * coords);
        sum += scale * noise.x;
        scale = scale / 2;
        s1 = s1 * 2;
    }

    return sum;
}

void main( void )
{
    float off_s = turbulence(vTexCoords.s, vTexCoords.t);
    float off_t = turbulence(1 - vTexCoords.s, 1 - vTexCoords.t);

    vFragColor = texture(edgeTexture, vTexCoords + vec2(off_s, off_t));
}

Clearly my addition to the vTexCoords is way off, but I can't see why.  I have tried several other turbulence function definitions but none were close to the desired output so I'm thinking my overall approach is flawed somewhere.  Any help here is greatly appreciated, and please comment if I haven't been clear.  The desired output for a torus would just look like a roughly drawn circle I would imagine.


texts:
I want to render a scene with an outline post processing effect in OpenGL ES 2.0.

First I render all the opaque objects. Then I use a post processing shader
for silhouette detection that uses the depth buffer as a texture.
 And now I want to render all the objects using alpha blending,
without writing to the depth buffer, but using depth testing with
the values from the depth buffer texture used for silhouette detection.

If I would have rendered the translucent objects before the post processing,
 the post processing would have rendered the outlines of opaque objects over
 them since they don't write to the depth buffer.

How do you tell OpenGL ES 2.0 to use a texture as the depth buffer?

Thank you


texts: b2DistanceJoint with frequency equal to 0 vs b2WeldJoint

texts: What is the difference of b2WeldJoint and b2DistanceJoint? They both have frequency and also when you put frequency of Distance Joint to 0 it acts like Weld Joint. It seams that you can create Distance Joint effect using Weld Jonit and vice versa.


texts: Where to find more documentation on Ogre3D?

texts:
I sucessfully managed to compile Ogre with MSVC2010 and I could dabble with the tutorials.

However, is there a website I am missing where there would be more ressources / infos?

The documention of the lib itself is very scarce and their wiki pages contain very few content, which is mostly outdated. For instance I'm trying to understand how the paging terrain manager works but I wasn't even able to find a single code snippet of a basic example, I don't even know which classes manage this effect.

So what's the best way to learn how to use Ogre? Are there some ressources outside of the main website?

Thanks


texts: Skinning, Bones, IK of character lost after Unity restart. Reproduceable

texts:
After i properly rig my character for skeletal animation with IK and everything works as expected but I quit my editor and restart, all bones are gone, IK does not correspond to the limbs and nothing works.

It is reproducible. What can I do?

Image is after restart and nothing works.


texts: faster compile and editor update in unity

texts:
sometimes for some small changes, I need to recompile the code In the editor and it causes some time to be testable in the editor(sometimes more than 20, 30 seconds).
I know when loading shows on the bottom-right side of the editor in means that it's compiling the code and when it doesn't move it means that it's updating the editor or checking for possible updates.
I need to know is there any way to make it faster? I mean, is there any option to tell unity don't recompile unchanged classes or don't consider all editor classes for changing the editor? or any other technique that makes the process faster?
as I use unit tests in the editor, most of the time is consumed by updating the editor for any added function or changes on them.


texts: Creating a basic character skeleton from code

texts:
I'd like to have a procedural system that uses a string of data to create a 3d creature. The way I've thought to do this is to use the code to generate a simple creature skeleton (I'll get to the skin generation when I have time) so I can test different source data's effect on the structure produced.

How can i use a set of data to generate the simple 3d skeleton?

The code would have information used to show what type of bone it was(hierarchy), the bone length, and how the bone was positioned and use this to make the model. (At least in planning, I don't know how to implement it)

Edit: The goal is to create creatures of different forms and skeletons. The creation will be mirrored down the spine so both sides are the same.

I'd like it to be highly adaptable but I'd like to specify a max of 4 legs and 4 arms (8 limb max only 4 on ground for walking). Being able to create a basic structure for humanoids, quadrupeds, and mixes (like a centaur or biped with no arms) is the goal.

I've looked for how to create a model off of the code procedurally, looking at stuff like FRep isosurfaces and metaballs, but I'm stumped on how to make it happen. I decided any progress is better that none, so I'd like to get a generator for something like an animators skeleton example to make sure I can get working structures (and later have something to work with to begin working on the animation algorithm).

Sorry for the lack of information at first, I was trying to keep the question simple. If you have an idea for the creation of the structure(skeleton) or maybe even the form itself I'd appreciate the help. Thanks


texts:
Can anyone point me to a possible implementation of the Photon network engine along with LibGDX for Android?  Or any multiplayer networking SDK for all that matters.

From reading source code it seems that Photon uses the native Android SDK heavily, like Intents and such, which are not provided through LibGDX.


texts: What type of network design should be used for my game?

texts:
Okay, so I am trying to design a multiplayer only game. Here is the gist of my multiplayer gameplay structure,

When a player starts up the game and clicks Play, he will be send to a map with 7 other players (i.e only total 8 players per map) who also just started the game like him.
It's basically like a deathmatch round. The last man standing is the winner.
The winner of the map will be transferred to another map which will consist of 7 other players like him who won their previous matches.  Note, the 7 losers of a match will be bought back to the main menu. When they click Play, they will start from the case mentioned in my first point.
And for the winners they will continue to play against winners from different maps.

So, my question is how to implement this network? Do I just need one main server? I am new to this so sorry if this question is very crude or stupid. Note, I just need a very high level network design considerations and suggestions.


texts:
As you see in picture, i cast rays to (vector3.right * direction) from center of boxCollider's bounds.
It can detect the wall mostly, but sometimes it can't detect the wall and pass through it.
the layer of wall is 'obstacle' and ray only detect that layerMask.
why this happend?

            moveAmount.x = input.x * speed;
            moveAmount.z = input.z * speed;

            directionX = Mathf.Sign(moveAmount.x);
            rayLength = Mathf.Abs(moveAmount.x) + .015f;

            if (Physics.Raycast(rayOrigin, Vector3.right * directionX, out raycastHit, rayLength, collisionMask))
            {
                Debug.Log("Hit");
            }


texts:
I'm using glfw in lwjgl-3 to try to create a toggleFullscreen method. However it always gives me errors. I saw this question Toggle Fullscreen at Runtime but it didn't help because glfwOpenWindow() and glfwCloseWindow() don't exist for me. I guess lwjgl uses a differnt version of glfw? Does anyone know of a good solution for toggling fullscreen? thanks. this is my current code if it helps.

    public void toggleFullscreen(){
        long newWindow;
        fullscreen = !fullscreen;
        if(fullscreen){
            newWindow = glfwCreateWindow(windowWidth, windowHeight, "Title", glfwGetPrimaryMonitor(), window.getWindowHandle());
            glfwMakeContextCurrent( newWindow );
        }else{
            newWindow = glfwCreateWindow(windowWidth, windowHeight, "Title", NULL, windowHandle());
            glfwMakeContextCurrent( newWindow );
        }
        glfwDestroyWindow(window.getWindowHandle());
        windowHandle = newWindow;

        glfwMakeContextCurrent(windowHandle);
        glfwSwapInterval(1);
        glfwShowWindow(windowHandle);
        GLContext.createFromCurrent();

        GL11.glEnable(GL11.GL_TEXTURE_2D);
        glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

        GL11.glViewport(0,0,windowWidth,windowHeight);
        GL11.glOrtho(0, windowWidth, windowHeight, 0, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        game.initInputPolling();
    }


texts: Finding average input value over time in seconds

texts:
I'd like to find the average input value from a controller over the last n seconds (say the last 0.1 seconds) and do this every frame.

I can see how to do this for the past n frames by storing a list of values for the last n frames and averaging that total every frame, but I want to account for a variable frame rate as the resulting output is driving a character controller and should feel precise and consistent. I tried storing a list of value pairs containing the input value and delta time value for every frame, then counting back through the list of delta time values until they sum to n seconds, then using the total of those input values to work out the average, but it seems a bit clunky and means I have to guess how big the list should be to store enough values, is there a better way?


texts: Access Entities components via the Entity that holds them, or via a separate System?

texts:
Now, I'm implementing a component based game engine and I came to a thought: Which way should I access my components?

Have a list of Entities, which have a list of Components, and access them by going trough each entity, and updating/drawing/whatever on each component.

or

Have separate systems for each component type and acces them by going trough that systems components.

Or does it really matter? I think that the second way would seem faster...


texts:
How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity?
I have a component with some scripts on it: Script1 and Script2. Inside the Script2.OnDestroy method I have the following line of code: GetComponentInParent<Script1>().
I want that line of code to return Script1 whenever I click the Play button inside Unity editor to stop my game. While right now it returns null.


texts:
I have trouble while detecting collisions on my 3D-Game.

I have set-up Rays, to detect collisions (Screenshot) and my main-rountine already analyzes them. But now there's the question what to do with that.

One possibility would be, to move the player back to the last position, but that's dirty, and does not work if the player can walk in multiple directions (e.g. if the player runs along a wall).

My question is, what to do with the collision data / or in which direction, by which amount move the player? I'm sure there is an algorithm for that (as for almost all is).


texts: Unreal Engine 5 Installation failed (MD-DL)

texts: I am getting an error while installing early access Unreal Engine 5 (error code: MD-DL). This is something about a manifest file. I am unsure about that. What is it about? I have deleted the previous download and tried it again, but popping the same message before initiating the download.


texts: Best portable console platform for game development?

texts:
I'm looking to experiment on a portable console platform ala Nintendo DS and PSP. But it could also be GP32, GP2X, GP2X Wiz or GP2X Caanoo.

So, before I go out and buy one, I'd like to hear from people who have experience with any portable console.

It would be best if each answer talked about one console with a link, pros, cons and personal experience (if any).

NOTE: I'm not looking for a mobile platform like iOS/Android/etc. I already know the answer to that: Android (I already have an Android device and I know Java). I'm specifically looking for a handheld console. See NopeAndNever's answer.


texts:
How to access/calculate worldNormal in a Vertex and Fragment shader ?

Thanks a lot !


texts: How can I make particles move like a square in Unity?

texts:
I would like to implement something like this in Unity:

I searched for how to implement such a functionality but only found stuff for circles which does not work with box shapes. How can I implement this?


texts: What is the term for collectibles which enhance storytelling (i.e. audio logs, bestiary entries, etc.)?

texts:
For example, Borderlands uses ECHO logs, there are audio entries in BioShock, RPGs often have "books" that you can collect pages to read a mini bonus story.

Is there a term more specific than "collectible" which conveys the element of storytelling?


texts: Eliminate unwanted "hills" in navmesh over a flat floor

texts: So in the image below you can see that my navmesh has these weird hills being formed in it. Any way to remove these? My AI gets stuck on them.


texts: Why do I have delays when pressing a keyboard key continuously to move the character?

texts:
What happens is I press right for a fraction of a second then release and my character moves to the right, as it is supposed to. I then press right again but this time for 5 seconds. My character moves immediately to the right and keeps moving with no pause between the first movement and the rest, as it is supposed to. But after 5 seconds of pressing right I then release the key and press left, but my character still keeps moving to the right for another 6 seconds. This effect is worse the longer I press the key. Why is that? I checked the boolean variables I am using to track the pressed and not pressed status of my keys and it seems like the status doesn't change until after the aforementioned 6 seconds during which the character keeps walking right although I am pressing left. However, key presses are still being detected quickly and on time in each iteration of the main game loop.

Based on my checks, key presses are still being checked quickly at each iteration of the main loop, and so is the key down/pressed status of keyboard keys. However, the key up/released status of keys is only checked until after the 6 seconds mentioned. Further checks showed that SDL2 poll event still reports a keydown status even though I am not pressing any keys and only reports a keyup after the 6 seconds. Is it windows 10 interfering with my program? It's like there's another program that keeps pressing right (same issue with other keys) eventhough I am no longer physically pressing that key.

I would appreciate your help and advice. Thank you.

I am programming in Free Pascal using SDL2. Below is a sample of my keyboard and other inputs procedure:

if sdl_pollevent(sdlevent)=1 then
begin
    { writeln(sdlevent^.type_,' ',sdl_keydown,' ',sdl_keyup); }
    if sdlevent^.type_=sdl_keydown then
    begin
        joystickactive:=false;
        { writeln(sdlevent^.key.keysym.sym); }
        { writeln(sdl_getkeyname(sdlevent^.key.keysym.sym)); }
        enterkeyintf:=false;
        if enterkeyintf=true then
        begin
            assign(t[1],'tf\tf0.tf');
            append(t[1]);
            settextbuf(t[1],bufin);
            writeln(t[1],sdlevent^.key.keysym.sym);
            writeln(t[1],sdl_getkeyname(sdlevent^.key.keysym.sym));
            close(t[1]);
        end;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=keycode[o[1]] then keybool[o[1]]:=true;
        until o[1]=totalkeys;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=alphanumm[o[1]] then alphanumbool[o[1]]:=true;
        until o[1]=totalalphanum;
    end;
    if sdlevent^.type_=sdl_keyup then
    begin
        joystickactive:=false;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=keycode[o[1]] then keybool[o[1]]:=false;
        until o[1]=totalkeys;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=alphanumm[o[1]] then alphanumbool[o[1]]:=false;
        until o[1]=totalalphanum;
    end;
end;


texts: Designing 1 on 1 battle: improving on Pokemon's model

texts:
Possible Duplicate:
  Designing AI in a 1 on 1 battle similar to Pokemon

I am developing an android game that uses a similar battle style to Pokemon.  Essentially you are going 1 on 1 against an opponent and you select from 4 moves to bring their health to 0.  I also will be implement items such as healing potions, antidotes etc.

My problem/question deals with how I can improve upon the simple battle system that Pokemon has.  What suggestions or ideas do you have that would improve gameplay and avoid everything becoming repetitive?

I've already come up with a couple ideas that I would like some feedback on.

Speed system - In pokemon, the speed stat for the most part only determines which pokemon attacks first.  I would like to implement as system where each monster has a speed stat that determines how often it can go and the monster with the lowest speedVariable goes next..  THe speed stat would be an arbitrary unit 1-100 that is added to the monsters speedVariable every time it makes an attack.  Also attacks have their own speed stat that gets added so high damage attacks add more time between attacks to provide balance.

FOr example: Monster A - 50 base speed, Monster B - 30 base speed
"Turn" one - B has lower speed so subtract difference and B gets to choose a move
           A(20) B(0)   - uses an attack that has a speed of 70. (0 + 70 + 30) = 100;
"Turn" two - A(20) B(100) figure out which goes next and adjust speedVariable
           A(0)B(80) - A uses a weaker attack with a speed of 25. (0+25+50) = 80
           A(75)B(80) - A would get to go again.

I also thought using statuses/debuffs to augment moves would be a nice addition.  If you use a fire attack on a monster it becomes burned for a certain number of turns.  Certain moves do extra damage (25-50%) when a monster has the burned status.  I also thought freezing/slowing with ice spells would increase a monsters speedVariable.


texts: Handle floating point precision errors in collision detection and resolution

texts:
I am experimenting with a continuous collision detection and response of points on a tile map.
This are my results for now:

I did this by shooting a ray (red line) from the current position (red circle) to the target position (green circle) and check all tiles which are on it using this algorithm.
If the ray hits a solid tile I calculate the exact postion of the collision (yellow circle) and a new target positition depending whether the ray hit the solid tile vertically or horizontally in the other case I can simply set the current position to the target position and be finished because no collision occurred.
Now I am shooting a second ray (blue line) to this new target position and check again for solid tiles on it.
If a collision occurerd I set the current position to the ray hit position (cyan circle) and be finished.
In the other case I only set the the current position to the new target position (cyan circle) because no collision occurred this time.

Here the most important source code:

void update(float start_x, float start_y, float target_x, float target_y, float *corrected_x, float *corrected_y)
{
    float hit0_x;
    float hit0_y;
    LineTraceResult res0 = line_trace(start_x, start_y, target_x, target_y, &hit0_x, &hit0_y);

    switch (res0)
    {
        case LINE_TRACE_NONE:
        {
            // No collision occurred so the target position is valid and we can move to it.
            *corrected_x = target_x;
            *corrected_y = target_y;
        }
        break;

        case LINE_TRACE_VERT:
        {
            // We hit a solid tile on the vertical edge.
            *corrected_x = hit0_x;
            *corrected_y = target_y;

            float hit1_x;
            float hit1_y;
            LineTraceResult res1 = line_trace(hit0_x, hit0_y, *corrected_x, *corrected_y, &hit1_x, &hit1_y);

            if (res1 != LINE_TRACE_NONE)
            {
                // There was a second collision on the corrected position so we need to adjust it.
                // Because the x axis did not changed we don't need to change it.
                *corrected_y = hit1_y;
            }
        }
        break;

        case LINE_TRACE_HORI:
        {
            // We hit a solid tile on the horizontal edge.
            *corrected_x = target_x;
            *corrected_y = hit0_y;

            float hit1_x;
            float hit1_y;
            LineTraceResult res1 = line_trace(hit0_x, hit0_y, *corrected_x, *corrected_y, &hit1_x, &hit1_y);

            if (res1 != LINE_TRACE_NONE)
            {
                // There was a second collision on the corrected position so we need to adjust it.
                // Because the y axis did not changed we don't need to change it.
                *corrected_x = hit1_x;
            }
        }
        break;
    }

So in theory this all works great but in practice there are a lot of problems caused by the limited precision of floats.

For example in this two cases:

One approach to "solve" this problem is to add some kind of padding often named Epsilon every time a collision occurs but this method seems to me not very accurate and dirty.

So I am wondering how all the professional game developers are solving this kind of problem?

EDIT:
This problems occurre because the hit position calculated by the ray can not be 100% exact so it could be for example that the y coordinate gets rounded from 6.9999 to 7.0001 and 6.9999 means tile 6 and 7.0001 means tile 7 so its a huge difference.


texts: How do I calculate the boundary of the game window after transforming the view?

texts:
My Camera class handles zoom, rotation, and of course panning.  It's invoked through SpriteBatch.Begin, like so many other XNA 2D camera classes.  It calculates the view Matrix like so:

public Matrix GetViewMatrix() {
    return Matrix.Identity
        * Matrix.CreateTranslation(new Vector3(-this.Spatial.Position, 0.0f))
        * Matrix.CreateTranslation(-( this.viewport.Width / 2 ), -( this.viewport.Height / 2 ), 0.0f)
        * Matrix.CreateRotationZ(this.Rotation)
        * Matrix.CreateScale(this.Scale, this.Scale, 1.0f)
        * Matrix.CreateTranslation(this.viewport.Width * 0.5f, this.viewport.Height * 0.5f, 0.0f);
}

I was having a minor issue with performance, which after doing some profiling, led me to apply a culling feature to my rendering system.  It used to, before I implemented the camera's zoom feature, simply grab the camera's boundaries and cull any game objects that did not intersect with the camera.

However, after giving the camera the ability to zoom, that no longer works.  The reason why is visible in the screenshot below.  The navy blue rectangle represents the camera's boundaries when zoomed out all the way (Camera.Scale = 0.5f).  So, when zoomed out, game objects are culled before they reach the boundaries of the window.  The camera's width and height are determined by the Viewport properties of the same name (maybe this is my mistake? I wasn't expecting the camera to "resize" like this).

What I'm trying to calculate is a Rectangle that defines the boundaries of the screen, as indicated by my awesome blue arrows, even after the camera is rotated, scaled, or panned.

Here is how I've more recently found out how not to do it:

public Rectangle CullingRegion {
    get {
        Rectangle region = Rectangle.Empty;

        Vector2 size = this.Spatial.Size;
        size *= 1 / this.Scale;

        Vector2 position = this.Spatial.Position;
        position = Vector2.Transform(position, this.Inverse);

        region.X = (int)position.X;
        region.Y = (int)position.Y;
        region.Width = (int)size.X;
        region.Height = (int)size.Y;

        return region;
    }
}

It seems to calculate the right size, but when I render this region, it moves around which will obviously cause problems.  It needs to be "static", so to speak.  It's also obscenely slow, which causes more of a problem than it solves.

What am I missing?


texts: How does a game like Minecraft handle block and entity updates?

texts:
I am not asking how Minecraft loads chunks or generates chunks, I am asking about individual blocks and entities and their behaviours.

Suppose you have a dirt block: dirt block can be converted to a grass block if there is a grass nearby. The game can have thousands of dirt blocks loaded at the same time, each checking if there is grass nearby.

Now add some monster spawners which have to spawn monsters periodically and keep track of how many monsters it spawned.

Then there is your large field of wheat, potatoes, carrots and saplings which the game also has to check and update every so often.

Then you have your furnaces that smelt your ores.

Then add into the mix all of the animals, monsters, villagers and their behaviours and pathfinding.

All of these actions are happening simultaneously and the game somehow keeps running smoothly on a decent computer.

How do the games generally handle this many block updates and entity behaviours? Does the game keep a list/collection of all the "updateable" blocks and just iterates every so often through that list and simply calls the ".update()" method? How are games with many updateable blocks/entities structured? Updating in a separate thread?

There are so many questions... Any clue is appreciated. Thank you.


texts:
using UnityEngine;
using System.Collections;

public class GunScript : MonoBehaviour
{
    public Transform barrel;
    public float range = 0f;
    public Rigidbody myBullet;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Rigidbody bulletInstance; // reference
            //make the bullet apear out of the barrel
            bulletInstance = Instantiate(myBullet, barrel.position, barrel.rotation) as Rigidbody;
            bulletInstance.AddForce(barrel.forward * range); //give the bullet some force to move forward
        }
    }
    IEnumerator Fire()
    {
        RaycastHit hit;
        Ray ray = new Ray(barrel.position, transform.forward);
        // in don't know how write this iff
        if (Physics.Raycast(ray, out hit, range))
        {
            Enemy enemy = hit.collider.GetComponent<Enemy>();
            enemy.health -= 1;
        }
        //Debug.DrawRay(barrel.position, transform.forward * range);
        yield return null;
    }
}

I made an enemy class, my bullet is a prefab, but i don't understand what i need to do to lower HP points when the bullet hits.


texts: How to develop a bot for a(n) (arbitrary) FPS game without a game API?

texts:
I've been interested in artificial intelligence in computer games for a long time. The question that I have been asking for a long time and to which I have not yet found an answer is the following: How to write a bot that can move through an FPS game without the game offering an API for developers? Is this possible by having only the information that the player sees on his screen? What options are there to implement something like this? Must the pixel information on the screen be processed by neural networks to operate object recognition (e.g., walls, doors, adversaries)? How can a bot, e.g. understand if he is running against a wall and is hanging on the wall? The bot would have to get a feedback about the fact that he just does not move forward in the world, because he hangs on the wall. So far I have not found an answer to these questions. For hints I would be very grateful, like also scientific articles.

As a supplement: The starting point for my question should be that you have no access to the source code of the game. Also, the game has no API through which the position data, environment data, etc. can be read.


texts: Unity - Button still interactable even when interactable is set to false

texts:
my button can still be pressed in-game even if I set it to button.interactable = false;

What I'm trying to achieve is when the Panel CropsPanel is opened, or active in Unity, I want the EquipmentButton to be disabled and to be not usable by the user. Here is the code I've written:

 public void Start ()
     {
         GetComponent<Button>().interactable = false;
         if (CropsPanel.activeInHierarchy == true)
         {
           EquipmentButton.interactable = false;
         }
     }

I have also set all buttons in the inspector, placed a Debug.Log("msg here"); to see if the particular code is working. But I can't seem to get it working. Am I missing something? Thanks guys!


texts: Copying a ID3D11Texture2D created by one device without the D3D11_RESOURCE_MISC_SHARED flag to another device

texts:
I'm writing a native plugin for Unity that is responsible for presenting the rendered Unity scene in a separate window with its own swap chain and an associated device and context all owned by the plugin. I'm rendering the Unity scene to a texture and passing the native pointer of the texture to the plugin. Had Unity's texture been created with the D3D11_RESOURCE_MISC_SHARED flag enabled, I could have simply accessed the texture using OpenSharedResource and created a ID3D11ShaderResourceView bound to it. But since Unity does not specify that flag at the creation of its texture, I need to copy that texture to another texture which is created with the D3D11_RESOURCE_MISC_SHARED flag enabled. I'm facing issues while doing this copy.

To test this pipeline, I'm working with the SpriteBatch example in DirectXTK tweaking it a little bit - create a texture using one device, and pass it on to another device (the original example uses the same device to create the first texture) which is responsible for rendering it on the screen.

I create a first texture from an image file using the first ID3D11Device1 without the D3D11_RESOURCE_MISC_SHARED flag enabled, and create a second empty texture using the second ID3D11Device1 with the D3D11_RESOURCE_MISC_SHARED flag enabled. Then I copy the contents of the first texture to the second texture, and create a ID3D11ShaderResourceView bound to the second texture.

ComPtr<ID3D11Resource> textureResource;
DX::ThrowIfFailed(CreateWICTextureFromFile(m_d3dDevice.Get(), L"cat.png", textureResource.GetAddressOf(), nullptr));

ComPtr<ID3D11Texture2D> cat;
DX::ThrowIfFailed(textureResource.As(&cat));

CD3D11_TEXTURE2D_DESC catDesc;
cat->GetDesc(&catDesc);

ComPtr<ID3D11Texture2D> spriteBatchTexture;
D3D11_TEXTURE2D_DESC sharedTextureDesc = catDesc;
sharedTextureDesc.Usage = D3D11_USAGE_DEFAULT;
sharedTextureDesc.Format = catDesc.Format;
sharedTextureDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED;
sharedTextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

//Create a texture which is a copy of cat, that belongs to the wicDevice but with a SHARED flag
DX::ThrowIfFailed(wicDevice->CreateTexture2D(&sharedTextureDesc, nullptr, spriteBatchTexture.ReleaseAndGetAddressOf()));
wicContext->CopyResource(spriteBatchTexture.Get(), cat.Get());

IDXGIResource* sharedResource(nullptr);
HANDLE sharedHandle;
DX::ThrowIfFailed(spriteBatchTexture->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource));
DX::ThrowIfFailed(sharedResource->GetSharedHandle(&sharedHandle));
sharedResource->Release();
DX::ThrowIfFailed(m_d3dDevice->OpenSharedResource(sharedHandle, __uuidof(ID3D11Texture2D), (void**)(spriteBatchTexture.GetAddressOf())));

D3D11_SHADER_RESOURCE_VIEW_DESC sbSRVDesc = {};
sbSRVDesc.Format = catDesc.Format;
sbSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
sbSRVDesc.Texture2D.MipLevels = 1;
sbSRVDesc.Texture2D.MostDetailedMip = 0;

DX::ThrowIfFailed(m_d3dDevice->CreateShaderResourceView(spriteBatchTexture.Get(), &sbSRVDesc, m_texture.ReleaseAndGetAddressOf()));

The m_texture is the ID3D11ShaderResourceView that is finally used by the example to render the image on to the screen.

The code goes through fine, but there's no image rendered onto the window when I do this.

Note: It does not seem to matter which device - m_d3dDevice or wicDevice I choose as the creator of the spriteBatchTexture. As long as OpenSharedResource is used properly, the code does not break but the end result is the same blank screen.


texts: How to access coordinates of objects in bullet physics (libGDX)?

texts: I need to access the x, y and z coordinates of a bullet physics object. I'm assuming this is done via the transform matrix, but I have no idea which values mean what. There doesn't seem to be any information about it on the internet. How is this done? Is there a better was of doing it that I'm not aware of?


texts:
Lightcycles or whatever it was called like.

Given a 2d array representing the game map, where each element can be either 0 or 1 (0 representing blank space and 1 representing filled space), what is the algorithm used for TRON enemy A.I?


texts: How to draw a sprite at a floating point xy coordinate with interlaced drawing?

texts:
I have a 2D game made in MonoGame (XNA 4.0 framework). Here's what I want to do:

draw a 2d image at a floating point xy coordinate such as 125.5, 300.12 (and do NOT round them to an int).
the image is automatically "interlaced", which means the picture is shaded correctly around the borders so that it looks like it's actually a fraction of the way across pixels, and not aligned exactly on pixels.

How do I do this? Is there a standard library for this?

P.S. the game I'm working on eventually needs to work on Mac and Linux as well, so please don't give me any dead-end solutions.


texts: Connecting smoothly N textures on terrain

texts:
I started to create my own terrain in a quite common way, just like this:  http://www.rastertek.com/tertut18.html . It is infinite and automatically generated (by using coherent noise). The areas are determined by using Voronoi noise (http://www.ctvisualeffects.com/renderman/maya_pattern_animation/cellnoise.jpg .

I am using triangle list with shared vertices. I'd like to create areas textured differently that are connected smoothly with each other. I came up with something like giving every vertex the texture id, e.g.:

0 - grass
1 - snow
2 - sand

I was thinking about sending the texture ids (the 0, 1, 2) to the shader in the TEXCOORD semantic (the z value), however I have no further idea on how to use them there to actually blend the textures smoothly.

Could you give me any hints, please? I'd be really grateful.

// EDIT

I ended up giving each vertex weights of each texture. But this is completely not generic solution and quite heavy as I have to change vertex structure when adding another area which has another texture.


texts: AutoFill function and methods not working in unity 5.3.5

texts:
I opened one of c# code in my projects, and edited something in the code, and I noticed that MonoDevelop no longer gives auto filling of function and method options.
Below is the screen shot of the code.When I type debug,its not showing the dropdown with list of function and methods.

Iam using 5.3.5 (64 bit)Personal and windows 8.
Can anybody help me sorting this issue.
When I open a c# code. its showing the namespace in redcolor

this is how the code structure looks


texts: How to implemement smooth side scrolling in a DOS game?

texts:
I'm about to develop (just for fun) a retro DOS game with Turbo C 2.01. Currently I'm wirting directly all the pixel information to 0xA0000000 + [y * 320 + x] which is very slow. My vision is to build a game which scrolls very smoothly over the tile map - just like this one (to name one example): http://www.doshaven.eu/game/dark-quest/.

I researched a bit online and found out that there is a attribute controller register where you can write to 13h a 4-bit pixel offset value.

inp(0x3da);
outp(0x3c0, 0x13 | 0x20);
outp(0x3c0, offset_in_x);

But it scrolls my screen only about 16 pixels and I read that this number is limited by the graphics mode (which I confirmed in some tests).

So how is this properly done?


texts: Ended up with left handed coordinate system OpenGL but I need right handed

texts:
So I started to make my own engine, and got my Z axis pointing away from my camera. I don't know why it happened, I followed this tutorial pretty much.

I'll post my persprojection and view calculations of my camera, please comment what other code should I post, and I'll update my post.

PersProjection

void Camera::setPerspective(float width, float height, float nearZ, float farZ, float angleDeg) {
perspectiveTrans.toZero();

float ar = width / height;

angleDeg = Math3D::ToRadian(angleDeg);

perspectiveTrans(0, 0) = 1.0f / (ar * tanf(angleDeg / 2.0f));
perspectiveTrans(1, 1) = 1.0f / tanf(angleDeg / 2.0f);
perspectiveTrans(2, 2) = (-nearZ - farZ) / (nearZ - farZ);
perspectiveTrans(2, 3) = (2.0f * farZ * nearZ) / (nearZ - farZ);
perspectiveTrans(3, 2) = 1.0f;
}

View and Projection calculations

Matrix4x4f Camera::getViewProjection() {
Matrix4x4f cameraRotationTrans(MatrixType::IDENTITY);

Vector3f N = target;
N.normalize();
Vector3f U = up;
U.normalize();
U = U.cross(target);
Vector3f V = N.cross(U);

cameraRotationTrans.setRow(0, Vector4f(U, 0));
cameraRotationTrans.setRow(1, Vector4f(V, 0));
cameraRotationTrans.setRow(2, Vector4f(N, 1));

Matrix4x4f cameraTranslationTrans(MatrixType::IDENTITY);
cameraTranslationTrans.setCol(3, Vector4f(-position, 1));

return perspectiveTrans * cameraRotationTrans * cameraTranslationTrans;
}


texts: How to Implement a Very Simple Game State Manager in Unity?

texts:
I’ve tried a bunch of different implementations, and trawled everything online I could get my hands on. Everything has downsides, nothing plays nicely with how Unity wants you to work.

Let’s keep it simple. You want to track in-game time. You want this to be available as a ScriptableObject. You need a MonoBehaviour to keep the time updated. You want to ensure there’s just one such GameState ScriptableObject and one such GameStateManager MonoBehaviour. You don’t want to manually add the manager to all scenes.

Is there a standard and sane way to achieve this without resorting to black magic?

To keep this grounded, here’s the boilerplate ScriptableObject:

    [CreateAssetMenu(fileName = "GameState", menuName = "ScriptableObjects/GameState")]
    public class GameState : ScriptableObject {

        /// <summary>
        /// The time passed in game, in game time, in seconds.
        /// </summary>
        public float TimePassed { get; private set; } = 0.0f;

        /// <summary>
        /// Moves the in-game time and date forward.
        /// </summary>
        /// <param name="addedGameTime">Time to add, in in-game seconds.</param>
        public void MoveTimeForward(float addedGameTime) {
            // Move the time passed forward
            TimePassed += addedGameTime;
        }

    }

And MonoBehaviour:

    public class GameStateManager : MonoBehaviour {

    /// <summary>
    /// The state of the game.
    /// </summary>
    public GameState gameState;

    // Start is called before the first frame update
    void Start() {
        // If we use a Singleton, and not drag a reference using the editor:
        gameState = GameState.Instace;
        // Mark that this should not to be destroyed when loading new scenes
        DontDestroyOnLoad(gameObject);
    }

    // Update is called once per frame
    void Update() {
        // Update the in-game time
        gameState.MoveTimeForward(Time.deltaTime);
    }

}


texts: How to put triangle information into a glsl shader for dynamic shadows?

texts:
I am experimenting with how much I can push the GPU with clever optimizations and correct use of hardware, so I know this may lag my computer a lot, that's not the issue.

Currently my goal is as follows:

Define a variable size structure (i.e an array) that contains floats, every 3 floats define a position vector, every 9 define a triangle.

I need to create an array of these structures (the array of all shadow casting objects currently loaded) and pass the array to the GPU (the glsl shader).

If I follow a couple of conventions when putting my data into this format I can use hashing to get an amortized constant search time for the shadow casting triangles,

The issue is to get the data into the format that I need. If this was C++ the format would be an array of vectors and we're done, but GLSL is not as good at managing memory, does somebody know a way to pass the information in the fashion I described, or am I trying to do something that can't be done?


texts: Changing the culling mode in the HLSL effect

texts: I'm writing a cel-shading effect in HLSL and Direct3D 11, and I need to be able to flip the culling mode on the outline pass of the effect.  I know you do this in XNA by setting CullMode to CW or CCW inside the pass definition, but is that how you do it in D3D11/SlimDX?


texts: Order independent transparency in particle system

texts:
I'm writing a particle system and would like to find a trick to achieve proper alpha blending without sorting particles because:

Each particle is a point sprite in a single mesh and I can't use scene graph ability to sort transparent nodes. The system node should be properly sorted, though.
Particle position is computed on shader from initial velocity, acceleration and time. In order to sort the system I would have to perform all this computations on CPU, which is something I want to avoid.
Sorting hundreds of particles against camera position and uploading it on GPU each frame seams to be quiet heavy operation.

Alpha testing seems to be fast enough on GLES 2.0 and works fine for non-transparent but "masked" textures. Still, it's not enough for semi-transparent particles.

How would you handle this?


texts: What is the difference between a HUD and a GUI in a game?

texts:
Does anyone know the difference between a graphical HUD (head-up display) and a GUI (graphical user interface) in a game? Is a HUD part of the GUI and just displaying information? That would mean that I can not technically interact with a HUD while I could with the GUI (e.g. clicking a button)? Or are both terms basically describing the same thing?

Note: I'm talking about these words while being ingame.

See the following example:

What would be described as GUI in this image and what as HUD?


texts: Calculating pitch angle to hit a target using a projectile that has fixed speed

texts:
I am trying to calculate a vertical angle needed to hit a target at [distance, elevation] 2D coordinates relative to shooter given a fixed projectile
velocity, air drag and gravitational acceleration.

Although I operate in 3D world (minecraft) the task itself eliminates the 3D problem. Once you calculate the rotation around your axis, which is in my case just atan2(-x3D, -z3D) what I'm solving is described on this picture:

From a wikipedia article about balistics I have picked this equation. As you can see, it seems to directly solve for my angle:

$$ \theta = arctan \bigg( \frac{v^2 \pm \sqrt{v^4-g(gx^2+2yv^2)}}{gx} \bigg) $$

So I rewrote the equation in javascript as Math.atan((v*v+Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/g*x); where v is speed, g is gravitational acceleration, x is distance and y is elevation of the target.

I implemented the whole algorithm as following:

//Assumed constants
var g = 9.81;  //Gravitational acceleration
var v = 35.9;  //Experimantally measured arrow speed
//The point of player head 3D [x,y,z]
var mepoint = this.bot.entity.position.offset(0, this.bot.entity.height, 0);
//The point of the target center assuming we're at [0, 0, 0] again using 3D [x,y,z]
var point = this.target.position.offset(0, this.target.height/2, 0).minus(mepoint);
//Transfer the coordinates with regards to the bot rotation
//That is, the 2D X coordinate is the distance as seen from the top
var x = Math.sqrt(point.x*point.x+point.z*point.z);
//The 2D Y coordinate is just plain difference between elevation
var y = point.y;
console.log("|BOT: TaskShoot| Target 2D coords [distance, elevation]: ",[x, y]);
//Calculate the horizontal angle - look at the target 3D [x,z] coordinates
var yaw = Math.atan2(-point.x, -point.z);

//Calculate the pitch using the equation from wikipedia
var pitch =  Math.atan((v*v+Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/g*x);
//Since it has 2 solutions, solve for bot + and - variant
var pitch2 = Math.atan((v*v-Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/g*x);
console.log("|BOT: TaskShoot| Angles: ",[pitch, pitch2]);
//NaN test: !(NaN>=0 || NaN<=0)
//Test two pitches and avoid NaNs. If both pitches are NaN, the target is out of range.
if(!isNaN(pitch))
  this.bot.look(yaw, pitch, false, function() {_this.finished();});
else if(!isNaN(pitch2))
  this.bot.look(yaw, pitch2, false, function() {_this.finished();});
else
  this.bot.look(yaw, 0, false, function() {_this.finishedError(123, "Couldn't calculate aim pitch - out of range? Aiming straight.");});

But this calculation allways returns almost the same values for the angles:

|BOT: TaskShoot| Target 2D coords [distance, elevation]:  [ 13.027689861406742, 3.032749999999993 ]
|BOT: TaskShoot| Angles:  [ 1.5704302724148764, -1.5643119398157057 ]

1.5704 is about pi/2. I never got significantly different result than this. So what's wrong with my calculation and how should I fix it? Did I even pick the right formula?


texts: Why does Unity increase the size of image when I use the image in Unity?

texts: I try to make a game in Unity 2d. But when I drop the image in Unity the image size increases 3 or 4 times. Can I fix that or is this normal?


texts: What the difference between public int and int?

texts:
I was trying to understand the difference of int and public int by checking how unity respond to it
using UnityEngine;
using UnityEngine.Assertions.Must;
using UnityEngine.SceneManagement;

public class Bird : MonoBehaviour

{
 int CurrentState = 1;
 int PreviousState = 1;

}
Void Update()
{(if CurrentState != PreviousState)
 transform.localScale = new Vector3(transform.localScale.x+1,transform.localScale.y+1,transform.localScale.z+1);
  }

Since the equality is false, the scale of object remail unchange and in my next step, I changed "int CurrentState = 1" to "public int CurrentState=0" and "int PreviousState = 1" to "Public int PreviousState = 1" . Isn't that this time, the equality is true as 1 !=0 but the scale of object remained the same. Once I deleted the word "public" on both currentstate and previousstate, the scale increase indefinitely. I thought the word "public" basically meant there no access restriction but why it looks like the "if" statement couldn't retrieve the info correctly?


texts: How to get xy coordinates along a given path

texts:
Say i have two points (x,y), (0,0) and (10,10). Now i wan´t to get coordinates along the line by stepping through values of x and y. I thought i solved it with the following functions:

 fy = startY + (x - startX) * ((destY-startY)/(destX-startX));
 fx = (y + startY) / ((destY-startY)/(destX-startX)) + startX;

taken from http://en.wikipedia.org/wiki/Linear_interpolation

However, it seems that im getting a problem when destX and startX is the same value, so you get division by zero.

Is there a better way of getting coordinates along a line when knowing the start and endpoint of the line?


texts:
I made this code because I needed an image to display a couple seconds after an enemy spawns, but for some reason I can't make it work.

There's no error in the console, but it doesn't display the image and I don't know what to do. Here's my script (it's attached to the enemy prefab)

 public class enemyAttack : MonoBehaviour {

 public float time = 5f;
 private IEnumerator coroutine;
 public Image image;
 private float t = 5f;

 void Start ()
 {
     //image.gameObject.SetActive (false);
     image.enabled = false;
     coroutine = nombredeCorutina (time, image);
     StartCoroutine (coroutine);
 }

 private IEnumerator nombredeCorutina (float t, Image im)
 {

     image.enabled = true;
     //im.gameObject.SetActive (true);
     yield return new WaitForSeconds (t);

     coroutine = nombredeCorutina (time, im);
     StartCoroutine (coroutine);
 }
}


texts:
I want to create a customized (modded) fps game where I can change the look and feel of the game to match my intended theme.

Some of the things I would like to do:

Create a custom map (terrain).
Add custom sound effects
Change AI (For example, running away instead of actively looking for combat).
Change menus and add some storyboard.
Script events in game (like a countdown until game over)
Change the models of the NPC's.

What options do I have? Is there any platform/game/engine/whatever that allows one to do the things above in a reasonable way?

I work as a programmer so I'm not afraid of coding some part of the project, but to save time it would be nice to work in some high-level way (like scripting or configuration files).


texts: How can I add word wrap to EditorGUILayout.TextArea?

texts:
How can I add word wrap to the editor textarea? I'm trying to mimic the [TextArea] attribute (word wrap, automatically increase height when needed)
For some reason GUILayout.TextArea() works fine, but EditorGUILayout.TextArea() doesn't have any word wrap. Here's my code:
obj.edibleFlavorText = EditorGUILayout.TextArea(obj.edibleFlavorText, GUILayout.MinHeight(textAreaHeight));

I've tried:

Adding GUILayout.ExpandHeight(true) to its options

Adding GUI.skin.textArea.wordWrap = true to the start of my editor script


texts: Trying to add my model's animation to the animator in Unity but it doesn't work?

texts:
I made an animation for a model in blender, then saved and imported it into Unity. In the preview, I can see the animation playing, but when I try to click on 'loop time' or to drag it over to the animator window, it doesn't work. In fact, I can't interact with it, other then drag the model into the scene. I'm not sure whether this is a bug, or if I've missed something with the settings. I am using 2.79

Does anyone know why this is, or has experienced anything similar? Also due to copyright reasons, I cannot upload any content from the game onto here.


texts: One framebuffer for each light vs unique framebuffer per light

texts:
Currently I have two ideas how to implement my lighting system:

1) Use one framebuffer per light source

no need to switch texture attachments of framebuffer
may be faster
bigger memory usage

2) Use one framebuffer for every light source

some time may be wasted on attaching new textures to framebuffer
less memory usage

So could you please tell me which way is better and why? Or I'm totally wrong on my thoughts and there is no difference at all?


texts:
So far i can understand that it is a  tree data structure consisting of multiple nodes.

If i draw an entity in world without any scenegraph, e.g. I have an object "Aircraft" which inherit from object "Entity"... so far so good i guess.

But what if i use scenegraph? if i draw an entity in world with scenegraph, i still have an object "Aircraft" which inherit from object "Entity" but now my object Entity inherit from a object "Node"? what is the diference? i still move my aircraft as the same without a scenegraph? or do i need to move node instead of aircraft?


texts: Using sky for indirect lighting - should I remove the sun?

texts:
I'm attempting to achieve slightly more realistic ambient lighting in outdoor scenes using the sky cubemap.

When rendering an object, I first calculate the direct lighting contribution using standard phong diffuse and specular shading from each light source. In outdoor scenes, this is usually a directional light used to model light from the sun.

I then add in the indirect diffuse lighting contribution by sampling a high mip level of the sky cubemap at the normal to the surface. However, it recently occurred to me that, since my sky cubemaps contain the sun, I am actually including the contribution from the sun twice! I'm introducing a directional light to model the sun in the direct lighting stage, then introducing further lighting from the skybox itself.

My question is this: Should I modify my sky cubemaps so that they don't include the sun, or should I just remove the directional light instead?


texts: Representation of trains on a simplified rail grid

texts:
I'm working on a hobby game, basically about train dispatcher's job.

(stack: Typescript, phaser.js)

My map is based on a grid, each tile can hold 1 rail tile (well, except junctions, but we can simplify it for now, since junctions are just multiple tiles, from which only one is active).

Example (black is grid, white is rail):

As you can see, we have basically three different tiles: straight rail, 45 degree turn and diagonal rail (which can be also considered straight rail). I don't plan to add more tiles, as you can already build pretty complex setups from these tiles.

On these rails, trains would drive. Each carriage has two "wheels" - positions, where it snaps to a track. This may be seen on the following example from my prototype:

However the existing system (see below) has some issues:

when a train travels diagonally, sometimes it's x and y coordinates fit in a field than it should (example: traveling from 1|1 to 2|2, but at one point the train's coordinates correspond to the field 1|2 or 2|1).
axles sometimes get closer or futher away from each other. This has almost no effect on resulting simulation (as the carriage is centered between those two axles), but may cause carriages to be closer or futher away from each other (this effect is visible on the prototype as weell)
moving the train in a certain direction is handled by a big chunk of code that essentially lists all possibilities of directions and handles it. I'm interested if there's a better way to do it, so I could simplify the code.

I decided that I would improve the core. I'm wondering, what would be the best way to do this?

What I am looking for:

how to save the rail pieces on the map?
how to move train (I know it's x, y, speed and acceleration)?
how to have the train continue to the next piece on the grid?

Current solution (broken in some edge cases, also not ideal):

each rail piece has it's class (CurvedRail, StraightRail)
each rail piece class has method movePoint, that accepts x, y, direction and distance and returns new point (that is distance away from the original point, but also considering track turns). It may also return delta, if the movement reached edge of the tile and it needs to be moved futher (on another piece). This is handled by a separate class, that finds the following rail piece and calls movePoint with the delta instead
it has issues, because sometimes trains passing diagonal connection don't exactly follow the diagonal, so they instead of ending up on the next diagonal piece, they end up on neighboring horizontal or vertical piece and derail.

One of the issues I may be facing is that tiles are 32x32 pixels, so it's hard to travel exactly in the "middle" of the piece, because it's "between two pixels", and although I'm using decimals, it may be a problem. Is it better to have a grid from odd-sized tiles?


texts: Java 2d game cross-platform compatability

texts:
I need to make a few small, simple 2d educational games primarily to help kids improve their reading. Drag & drop/matching words with pictures, spelling out words as well as maybe a scrolling shooter and some other things too. I also need these to run on multiple platforms (namely windows, osx, ipads and android).

If I do this with java (which I don’t currently know), is it possible to use the same code to create versions compatible with the above-mentioned platforms?


texts: Help generating clues in a treasure finding game

texts: I am a high school student creating a small game in unity for fun and would greatly appreciate your opinions on this game mechanic. I have a treasure finding game that takes place in a randomly generated forest with randomly placed treasure. There are also randomly placed landmarks such as large rocks, lamp posts, picnic tables, etc. The treasure spawns within a certain radius of a landmark as to provide a reference point for clues to the position of said treasure. I am having some difficulty however, deciding what sort of clues i could generate. I thought of a few ideas such as generating clues referencing a landmark the treasure is near, clues referencing cardinal directions, and clues which are an image of the treasure's surrounding environment. I would love some feedback on the clues i have thought of so far, and new suggestions for clues. Thanks in advance!


texts: I am making a java game using path geometry. Is there any way to save the data stored in a Path2D to a file?


texts: How to setup for live player / observer pair w/ voice chat in Minecraft

texts:
I'm trying to build a setup for educational use of Minecraft:

One person plays Minecraft, another person watches live online with the least lag/latency possible, and the pair can talk over high-quality voice chat.

What is the best setup to allow this?

Scenario A:

1) Write a mod that allows a watcher to be a passive spectator through their copy of Minecraft? The watcher would see exactly what the player sees.  Would this be the fastest and clearest picture? Is it a trivial mod to write?

2) Connect together over Hamachi? Can that be dead-easy to set up?

3) Use a voice-chat in the game itself?

Scenario B:

1) Use a streaming video technology. (Twitch? Google Hangouts? Something else?)

2) Third party voice chat like Skype. (Or just Google Hangouts?)

My fear here is lag, low quality video, bandwidth.

Scenario C ?

Thanks very much for any help :)


texts: How to draw a line based on an angle with a defined size?

texts:
I have a game where the player shoots a projectile based on the mouse direction when clicking, which travels 500 pixels.

I wish I could draw a line exactly where the projectile will be destroyed.

What I can do is draw a line from where the projectile is created to where the mouse is when it is clicked.

That is, the line may be longer or shorter than the path taken by the projectile.

The code is something like this:

draw_line(x,y,mouse_x,mouse_y);

Result in game:

Below an image explaining:

These blue dots would be the click of the mouse. That no matter where it went, the line drawn (green) would be the same (ending in pink x).

I know how to get the direction and how to calculate the distance, but I don't know how to implement it in line drawing.


texts: How effects found in "Autodesk Fluid FX" are implemented using OpenGL ES?

texts:
How this kind of effects are technically implemented using OpenGL ES? Are they performing simulation on GPU (using Shaders) or CPU while using some smart vertex positioning and texturing? Why it appears so fast (in terms of performance)?

You might check the video of that app here: http://www.youtube.com/watch?v=F4KOk6QP6kQ

edit

Here is the presentation for the app: http://www.futuregameon.com/FGO2010_JosStam.pdf


texts: How can i press the key, show the text and choose if i want to take the item?

texts:
It's working fine right now, showing the text and then press the key and it takes the item but, i want something like resident evil, the text is not showing until you press acction button. How can i do that?

The key script:

var TheKey : GameObject;
private var playerNextToKey = false;
//var showMessage : boolean = false;
//var nearKey : boolean = false;
 var hasCollided : boolean = false;
 var labelText : String = "";

 function OnGUI()
     {
         if (hasCollided ==true)
     {
          GUI.Box(Rect(140,Screen.height-50,Screen.width-300,120),(labelText));
     }
 }

function Update ()
{
    if (Input.GetKeyDown(KeyCode.E) && playerNextToKey == true)
    {
    TheKey.active = false;

    }
}

function OnTriggerEnter (theCollider : Collider)
{
    if (theCollider.tag == "Player")
    {
        //nearKey = true;
        playerNextToKey = true;
        hasCollided = true;
        labelText = "¿Vas a coger la llave?";

    }
}

function OnTriggerExit (theCollider : Collider)
{
    if (theCollider.tag == "Player")
    {
        //nearKey = false;
        playerNextToKey = false;
        hasCollided = false;

    }
}


texts: I am creating a maze game in c++. I have a class that is used to create the walls with positioning and collision. I want the user to have the capability to include the header files needed for making the walls into a separate map file, and then be able to upload that file to the game without having to recompile the game itself. Should these map files be separate .exe or some other compiled file? could they be regular .cpp files that the game just reads? A friend suggested dynamic libraries, but that doesn't seem quite right.


texts: Why is my Tiled map distorted when rendered with LibGDX?

texts:
I have a Tiled map that looks like this in the editor:

But when I load it using an AssetManager (full static source available on GitHub) it appears completely askew.

I believe the relevant portion of the code is below.
This is the entire method; the others are either empty or might as well be.

private OrthographicCamera camera;
private AssetManager assetManager;
private BitmapFont font;
private SpriteBatch batch;
private TiledMap map;
private TiledMapRenderer renderer;

@Override
public void create() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    assetManager = new AssetManager();
    batch = new SpriteBatch();
    font = new BitmapFont();

    camera.setToOrtho(false, (w / h) * 10, 10);
    camera.update();

    assetManager.setLoader(TiledMap.class,
            new TmxMapLoader(
                    new InternalFileHandleResolver()));
    assetManager.load(AssetInfo.ICE_CAVE.assetPath, TiledMap.class);
    assetManager.finishLoading();

    map = assetManager.get(AssetInfo.ICE_CAVE.assetPath);

    renderer = new IsometricTiledMapRenderer(map, 1f/64f);
}


texts:
In Unity, what is the correct way to move a game object by modifying the velocity of its rigidbody?
I'm having some issues with stuttering movement, so I just want to make sure I understand the basic idea. Is the following correct for moving an object vertically down the screen? Should this result in smooth, stutter-free movement?
using UnityEngine;

public class MovementTest : MonoBehaviour
{
    private Rigidbody2D rb;

    [SerializeField] private float speedY = -250;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        rb.velocity = new Vector2(
            0,
            speedY *  Time.fixedDeltaTime
        );
    }
}

```


texts:
I'm making a text-based RPG in C++ just for fun, and in a way that I can keep adding to it and hopefully give it graphics one day, and I've got a lot of code for everything. My only problem is that I can't come up with a decent way to create enemies that will be fair across the levels and classes. Tweaking the formulas doesn't seem to help. I will give some examples, there are only 10 enemies now, and I'm just wondering if anyone has a better way of going about this that keeps the variety between classes and fairness across levels. Here are a few of the monsters:

    Monster.Name = "Minotaur";
    Monster.monsterOption = random1;
    Monster.level = Player.level;
    Monster.health = 30+(5*Monster.level)+(rand()%7);
    Monster.workinghealth = Monster.health;
    Monster.attack = 15+(7*Monster.level+(rand()%4));
    Monster.defense = 26+(11*Monster.level)+(rand()%4);
    Monster.speed = 10+(2*Monster.level)+(rand()%3);
    Monster.luck = 2+(1*Monster.level)+(rand()%1);
    Monster.accuracy = 90+(rand()%5)-(rand()%10);
    Monster.gold = (rand()%120)+(30*Monster.level);

    Monster.Name = "Bandit Leader";
    Monster.monsterOption = random1;
    Monster.level = Player.level;
    Monster.health = 20+(2*Monster.level)+(rand()%15);
    Monster.workinghealth = Monster.health;
    Monster.attack = 20+(7*Monster.level+(rand()%3));
    Monster.defense = 20+(10.5*Monster.level)+(rand()%3);
    Monster.speed = 20+(4*Monster.level)+(rand()%8);
    Monster.luck = 2+(1*Monster.level)+(rand()%1);
    Monster.accuracy = 90+(rand()%5)-(rand()%10);
    Monster.gold = (rand()%150)+(32*Monster.level);

    Monster.Name = "Dragon";
    Monster.monsterOption = random1;
    Monster.level = Player.level;
    Monster.health = 35+(4*Monster.level)+(rand()%10);
    Monster.workinghealth = Monster.health;
    Monster.attack = 20+(7*Monster.level+(rand()%10));
    Monster.defense = 25+(11*Monster.level)+(rand()%10);
    Monster.speed = 20+(1*Monster.level)+(rand()%10);
    Monster.luck = 2+(1*Monster.level)+(rand()%6);
    Monster.accuracy = 90+(rand()%5)-(rand()%10);
    Monster.gold = (rand()%100)+(30*Monster.level);

So you can see the formulas aim to keep some degree of randomness between each of the same type of monster, and they should be changed based on your level but not your class, weapons, armor, etc. That is all the information about each kind of monster while there is more information about the player (Armor and weapons added to base defense and attack). Here is an example player from a file I have saved right now:

           SAVED CHARACTER INFORMATION
================================================
| Name:     WarriorRawrry                      |
| Class:    Warrior                            |
| Level:    32                                 |
| Health:   207/241                            |
| Attack:   231                                |
| Defense:  159                                |
| Speed:    159                                |
| Luck:     45                                 |
| Accuracy: 90%                                |
| Exp Pnts: 1228/16000                         |
| Gold:     7183                               |
| Weapon:   Sword of 1000 Truths  +125 attack  |
| Chest:    Blinding Breastplate  +90  defense |
| Legs:     Oblivion Greaves      +88  defense |
| Helmet:   Crown of Death        +64  defense |
| Hands:    Gauntlets of Fate     +54  defense |
| Feet:     Hell's Sabatons       +60  defense |
================================================

Note: That is output from the command line, I just put it in code format to make it easy to read.

So you guys can see what I'm trying to accomplish here, I'm not asking you guys to create math formulas for me, but any ideas on what would be a better way to go about this would be much appreciated.


texts: A*Pathfinding lose target after spawning from script?

texts:
I have been using A*Path finding to enable object tracking. It works fine if I have both objects on the scene at the same time.

However, if I were to use a script to spawn the seeking object instead, it will only track the first path to the object and not repath again.

I am using the default AI Follow script and a prefab variable as the object to be tracked (which is an empty child game object to a moving character).

Code :

import Pathfinding;

//var tankTurret : Transform;
var tankBody : Transform;
//var tankCompass: Transform;
var turnSpeed : float = 10.0;

var targetPosition : Vector3;
var seeker : Seeker;
var controller : CharacterController;
var path : Path;
var speed : float = 100;
var nextWaypointDistance : float = 3.0;
private var currentWaypoint : int = 0;

function Start()
{
    //targetPosition = GameObject.FindWithTag("GTO").transform.position;
    GetNewPath();
}

function GetNewPath()
{
    Debug.Log("GETTING NEW PATH!");
    seeker.StartPath(transform.position,targetPosition,OnPathComplete);
}

function OnPathComplete(newPath : Path)
{
    if(!GetNewPath.error)
    {
        path = newPath;
        currentWaypoint = 0;
    }
}
function FixedUpdate()
{
    if(path==null)
    {
        return;
//          Debug.Log("NO PATH!?");
    }
    /*if(currentWaypoint >= path.vectorPath.Length)
    {
        return;
    }*/

    var dir : Vector3 = (path.vectorPath[currentWaypoint]-transform.position).normalized;

    controller.SimpleMove(dir);

    //tankCompass.LookAt(path.vectorPath[currentWaypoint]);
    //tankBody.rotation = Quaternion.Lerp(tankBody.rotation, tankCompass.rotation, Time.deltaTime*turnSpeed);

    if(Vector3.Distance (transform.position,path.vectorPath[currentWaypoint]) < nextWaypointDistance)
    {
        currentWaypoint++;
    }

}

Any help will be greatly appreciated.


texts: How to get surface position from 3D objects in 2D space

texts:
I am working on simple drag and drop game with JavaScript and PixiJS. The game itself is 2D, but I have some pseudo-3D objects (I guess isometric) and I am trying to get the position of those objects.

My question is if there is any mathematical equation or algorithm to solve my problem:

I have some fruit objects, and the user should put those objects in the basket I have below, but only in the yellow surface like below in the picture. Currently, I am using the code below to check if the object is inside the basket or not, but this checks the entire texture and not the yellow surface!

isInside()
{
    if (this.object.x > basket.x1 && this.object.x <= basket.x2 &&
        this.object.y > basket.y1 && this.object.y <= basket.y2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Which algorithm can I use to check only the yellow surface?


texts: Can I add extra widgets to a child widget in UMG-UE4?

texts:
I have a widget base class and I would like to reuse (logic and wigdets as well) it.
I created an empty widget and set the parent class to the base class I would like to inherit from in the class settings.
Works fine.
But when I am trying to add any widget on top the pre-existing ones just disappear, they get overridden by the children, I guess.
I found this post for a feature request, but it is quite old.
Just wondering if it is possible to add extra widgets without getting rid of the parent ones?


texts: Detecting if an object is following a path

texts:
I am attempting to take GPS data and track it on a map and see if it follows a given path. I have the path as a set of points and the GPS data streams in as a similar set of points. I am attempting to track the progression of the current position across the path and I am wondering if there are any well known algorithms for this. I have come up with my own that works ok but it is a complex enough problem that I would like to minimize the amount of re-inventing of the wheel that I do.

What approach or algorithm would you recommend taking for this problem?


texts: Server-side Architecture for Online Game

texts:
basically I have a game client that has communicate with a server for almost every action it takes, the game is in Java (using LWJGL) and right now I will start making the server.

The base of the game is normally one client communicating with the server alone, but I will require later on for several clients to work together for some functionalities.

I've already read how authentication server should be sepparated and I intend on doing it.
The problem is I am completely inexperienced in this kind of server-side programming, all I've ever programmed were JSF web applications.

I imagine I'll do socket connections for pretty much every game communication since HTML is very slow, but I still don't really know where to start on my server.

I would appreciate reading material or guidelines on where to start, what architecture should the game server have and maybe some suggestions on frameworks that could help me getting the client-server communication.

I've looked into JNAG but I have no experience with this kind of thing, so I can't really tell if it is a solid and good messaging layer.

Any help is appreciated...
Thanks !

EDIT:

Just a little more information about the game. It is intended to be a very complex game with several functionalities, making some functionalities a "program" inside the program.
It is not an usual game, like FPS or RPG but I intend on having a lot of users using these many different "programs" inside the game.

If I wasn't clear enough, I'd really appreciate people that have already developed games with java client/server architecture, how they communicated, any frameworks, apis, messaging systems, etc.

It is not a question of lack of knowledge of language, more a question for advice, so I don't end up creating something that works, but in the later stages will have to be rewriten for any kind of limiting reason.
PS: sorry if my english is not perfect...


texts:
I'm developing a game in Python with Kivy as the gui. I've heard a few programs mentioned that compile python files to .exe's. However, I cant seem to find any that mention compiling .py and .kv files.

I wish to eventually publish my game to Steam Direct but i would like to know if my current approach to coding the game will hinder me doing so.

My actual question is, is there a way to compile a Python game with Kivy to an .exe file?


texts: How to create an array of images on a canvas

texts: I am developing a game that uses different images.When am image is swiped to the bottom of the screen it disappears and a new image appears at the top.Seeing as you can't delete an individual image I want to clear the canvas and redraw the images from an array of images. My question is how do you create an array that is accessible from the onDraw method?


texts:
I am trying to display the first two bytes of a binary file as a test. I have the following code.

 void DisplayValuestext(){
  Stream s = new FileStream("Assets//testbinary.bin", FileMode.Open);
  BinaryReader br = new BinaryReader(s);
  int dataVal = br.ReadUInt16();
  Debug.Log(dataVal);
 }

The first 2 bytes of the binary file are "1E44" which the function ReadUInt16() should read. However, it reads the first byte of data, "1E" rather then the first 2 bytes "1E44". I believe it is because it reads 2 characters, rather than 2 bytes. When I display the 16 bit unsigned integer "dataVal" in the console, I get 25905. The value I am trying to get is 17438 which is "1E44" little-endian encoded value converted to decimal.

I have also attempted to use the function "ReadUInt32". This method should read the first 4 bytes, however it instead displaces by 4 characters, which is 2 bytes "1E44". The console displays "875849009".

Why do I get these strange values "25905" and "875849009" and how can I resolve this to get the desired value of 17438?


texts: Would it be worth designing games in which the fighting is suspended so your enemies can get some sleep?

texts:
I think one way to motivate kids to get more sleep at night would be to design a series of video games in which the monsters/creatures/aliens, etc., will automatically stop attacking your character between the hours of say 11:00pm - 7:00am.

At 11:00pm, they will cease fighting, will lay down and fall asleep. At 7:00am, they will wake up and resume attacking your character. If you attack them while they are sleeping, you will lose major points or you will instantly die.

Also, you will need to instruct your character to go to sleep during this same period, or your character will be very sleepy when the game resumes and will not perform well.

This particular time period would need to be hard coded into the game so it cannot be changed. So, at 11:00pm in New York City the enemies in the game will go to sleep, and the same thing happens in the game at 11:00pm in Los Angeles, and so forth in all the time zones around the world.

Would it be worth adding this feature to video games or would most kids just refuse to play them?


texts:
I want to get the object color, when I start the game. How do I do this?

public Renderer cube;
public float r,b,g,a;

void Start() {
            r = cube.GetComponent<Renderer>().material.color =
            b = cube.GetComponent<Renderer>().material.color =
            g = cube.GetComponent<Renderer>().material.color =
            a = cube.GetComponent<Renderer>().material.color =

}


texts: I'm having trouble understanding the benefit of the newer GL_EXT_draw_instanced over traditional VBO's.  Don't both keep geometry cached on the gpu for faster redrawing?  VBO's seem much more flexible.


texts: How to use a sprite mask or shader to mask a text?

texts:
I'd like to know what I need to learn to apply a shader to achieve masking on the text.

Here is my text object in-game, I'm using a sprite mask to mask the game objects on the card, they're all in their own sorting layer, the order number is 11.

Here is my text in the inspector

However, everything on the card is being masked except the text.

If someone could tell me what I need to learn to solve this problem that'd be great, can this problem be solved using a shader?


texts: Load different grayscale images into the same texture

texts:
I have a series of images loaded as

data1 = stbi_load_from_file(file1,&width,&height,&comp,1);
data2 = stbi_load_from_file(file2,&width,&height,&comp,1);
data3 = stbi_load_from_file(file3,&width,&height,&comp,1);

So that they're grayscale images. I then want to load these three images into a single GL_RGB texture. How can I do this? Do I have to allocate new memory and create a new image picking the channels info from the three different images?


texts:
Few days ago , we learned about Homogeneous Matrices in OpenGL class.
From what I have understood , using these matrices we can convert 3D objects to 2D.
However , I am facing some difficulties answering a simple question like : "Which of those matrices answering to the definition of converting from 3D to 2D (Homogeneous)" :

           A                         B                      C               D

I'm not asking you to do my homework, I know the answer it's D and C and this is all I need for this section. I just want to understand why? how it works? why A,B not and C,D yes.
Thank you.


texts: If I use someone else's idea (not work, an *idea*), do I have to give them credit?

texts: Ideas are everywhere for games, products, algorithms, etc. In hypothetical terms, let's say user number x posts on (insert social media site here) that they would like to see a game about (insert game topic here). Can I take their idea and formulate it into a game without giving them any credit?


texts: How to draw the player standing behind a tree in an Entity Component System?

texts:
I'm making a top-down Javascript canvas game using the Entity Component System architecture.
For an entity to be drawn on the screen every frame, it needs a PositionComponent and a SpriteComponent. The rendering system looks like this:
for (let entity of scene.query(CT.Sprite, CT.Position)) {
  this.drawEntity(entity);
}

This works well, but I'm not sure how to modify this to give the player the ability to hide behind objects. For example, in Stardew Valley, you can stand in front of, and behind, objects, as demonstrated in this screenshot: https://i.imgur.com/B90jGS7.png
How can this be implemented in an ECS? Because currently my rendering system just iterates through every object and draws them.
Also, currently, for drawing the map (scenery and whatnot), it renders the map to a texture and then just redraws that single texture every frame (for performance reasons, instead of redrawing 10,000 tiles every frame). I'd imagine this makes it even more difficult to integrate.
My assumption is that I have to take into account the entity's position in some way? That is, an entity with { x: 0, y: 400 } will be drawn before an entity with position { x: 0, y: 500 }, but I'm also unsure of how to integrate this with an ECS.
Thanks for reading.


texts: MonoGame rendering text with black boxes?

texts:
I have a UI manager that renders a background image and some images and buttons using BlendState.AlphaBlend. This works as intended. However, when I try and draw some text on top of it with the same BlendState, each character is encased in a black box and it looks awful. I played around a bit and found that BlendState.Additive was the only one that didn't render the black boxes. However, the text is now slightly transparent, which looks weird. I then decided to mess around with custom BlendStates, but after around 10 minutes I found that there could be over 67 million different BlendStates. Hmm. My last thought is that it could be the font that is breaking it, because I tried rendering with the Arial font and AlphaBlend worked fine. Is there a way round this using BlendStates without finding a new font?

tl;dr I can only render text either with black boxes or half transparent.

Text rendering code:

sb.Begin(samplerState: SamplerState.PointClamp, blendState: BlendState.AlphaBlend, transformMatrix: Game.Camera.GetViewMatrix());

sb.DrawString(Game.Font, text, position, color);

sb.End();

SpriteFont File (using the free Minecraftia font):

<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">
    <FontName>Minecraftia</FontName>
    <Size>6</Size>
    <Spacing>0</Spacing>
    <UseKerning>true</UseKerning>
    <Style>Regular</Style>
    <DefaultCharacter>?</DefaultCharacter>
    <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#126;</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

It's a pixelly game (so I need a blocky font to avoid weird antialiasing) and I think the font is a bitmap font. Just in case that makes a difference.

Edit: I found that setting the text size (in the SpriteFont file) to anything other than it's native size fixes the problem (but also renders with antialiasing, which I don't want). Also, this problem seems to happen with other bitmap fonts (tested 'Minecraftia' and '04b03').


texts:
How exactly (or, how often) are textures passed to the GPU shaders in MonoGame/XNA?

I am asking because I was profiling a MonoGame/XNA application and noticed that the memory controller load (using GPU-Z) was pretty high.

After disabling pretty much everything except the background texture (a static 24-bit 1920x1080 image), my frame rate went up as expected (~500fps) with GPU load peaking at 99% - but what surprised me was that the GPU memory controller load remained at ~50%.

Setting the breakpoint inside TextureCollection.PlatformSetTextures confirmed that SpriteBatch is indeed passing this texture to the pixel shader on each call.

Does this really mean that all textures are being passed to GPU on each frame over and over again? Am I misinterpreting these readings, or have a fundamentally wrong understanding of how the rendering process should work? Or did I mess something up with my Draw calls?