texts: XNA 3.1 to 4.0 Vertex Shader Not Drawing

texts:
I have recently been converting our XNA 3.1 game to XNA 4.0 and am stuck on the shaders.  I have the game running, but nothing is drawing to the screen, except things not using a shader.

This is only 2D drawing, using SpriteBatch, which im sure is where the problem is coming from.

In XNA 3.1 everything works fine with my custom vertex and pixel shaders targeting SM 3.0.  I cant find any info on what has changed or why its not working.  Ive stripped it down as far as I can to try to figure it out, but am not sure.  It definitely seems like a coordinate issue with the vertex shader.  If I strip our the vertex shader and switch to SM 2.0 for the pixel shader so it uses XNAs default vertex shader for SpriteBatch, it works as expected, but I need 3.0 and custom vertex shader functionality.

Here is stripped down version of things, I cant get PS to output anything anywhere:

// Input parameters.
float2   ViewportSize    : register(c0);
float2   TextureSize     : register(c1);
float4x4 MatrixTransform : register(c2);
sampler  TextureSampler  : register(s0);

struct VS_INPUT
{
    float4 position : POSITION0;
    float4 color    : COLOR0;
    float2 texCoord : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4 position : POSITION0;
    float4 color    : COLOR0;
    float2 texCoord : TEXCOORD0;
};

struct PS_INPUT
{
    float4 color    : COLOR0;
    float2 texCoord : TEXCOORD0;
};

VS_OUTPUT VertexTileShader(VS_INPUT input)
{
    VS_OUTPUT output = (VS_OUTPUT)0;
    float4 position = input.position;

    // Apply the matrix transform.
    output.position = mul(position, transpose(MatrixTransform));

    // Half pixel offset for correct texel centering.
    output.position.xy -= 0.5;

    // Viewport adjustment.
    output.position.xy /= ViewportSize;
    output.position.xy *= float2(2, -2);
    output.position.xy -= float2(1, -1);

    // Compute the texture coordinate.
    output.texCoord = input.texCoord / TextureSize;

    // Pass on color
    output.color = input.color;

    return (output);
}

float4 PSTileLighting(PS_INPUT input) : COLOR
{
    return float4(1.0, 1.0, 1.0, 1.0);
}

technique TileLighting
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertexTileShader();
        PixelShader = compile ps_3_0 PSTileLighting();
    }
}

C#:

// Setup matrix
transform = Matrix.CreateTranslation(-bounds.X, -bounds.Y, 0);

// Setup viewport
SectionViewport.X = 0;
SectionViewport.Y = 0;
SectionViewport.Width = bounds.Width;
SectionViewport.Height = bounds.Height;

Engine.GraphicsDevice.SetRenderTarget(background);

Engine.GraphicsDevice.Viewport = SectionViewport;
Engine.GraphicsDevice.Clear(Color.Transparent);

Map.TilesEffect.CurrentTechnique = Map.TilesEffect.Techniques["TileLighting"];

Vector2 viewportSize = new Vector2(SectionViewport.Width, SectionViewport.Height);
Map.TilesEffect.Parameters["ViewportSize"].SetValue(viewportSize);
Map.TilesEffect.Parameters["TextureSize"].SetValue(new Vector2(2048, 2048));

Engine.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, Map.TilesEffect, transform);
DrawTiles(tileLayer, 0, 5, bounds, Color.White);
Engine.SpriteBatch.End();

DrawTiles calls the draw function on all the tiles within the bounds rectangle.  They are all in a large 2048x2048 sprite sheet.  Map is broken up into blocks of these which the transform matrix is used to offset.

This all works in XNA 3.1.  I stripped the pixel shader to absolutely nothing, just outputs white (or is supposed to).  Im sure its not any of the specific drawing code because like I said if I switch to the default SpriteBatch vertex shader (IE not defining one, and rolling the PS back to 2.0). Then it works as expected.  It draws white pixels everywhere it should.

There must be something wrong im doing with the matrix / viewport manipulations, but am not sure what.  Ive looked at SpriteBatches default shader, but it uses a lot of macros and sets the matrix up before going to the shader and not sure how to correlate it with mine.

Any help is appreciated, thanks.


texts: How to assign xNode graphs to an active object?

texts:
I am trying to create a basic AI using the xNode visual scripting tool.

The getting started guide from github is not showing how to assign the created graphs to an active object (if this is even how it should be done).

How do I let my graph control a specific object?


texts: How do I generate projectiles toward the mouse pointer?

texts: I'm making a top-down space shooter where the player controls a ship and can aim and shoot using the mouse cursor. How can I fire bullets from the ship at the angle from the ship to the mouse cursor?


texts:
In space invader, I'm doing bullet to barrier intersection using rect to rect, then I'm testing the first bullet's impact pixel, if it's green I blast a circle, if it's black, it continues travelling. now there is a situation that there is part of the barrier that won't be checked for intersection, as shown in the image, the first intersection test will fail, because the first pixel is black...

How would I resolve that issue ?


texts: How do I implement smooth movement in a Box2D platform game?

texts: I have implemented a character in JBox2D which moves with the help of a wheel rotating at the bottom of it. The movement is the best result I've had 'till now but it's a little glitchy when the character stands on the edge. So I am thinking should I use five smaller wheels instead of a big wheel. The wheel/wheels will not be visible in the finished product, now they are drawn for debugging. Here is a video. Is there a better way to do this using JBox2D?


texts: Unity built-in Network Lobby How to move GUI?

texts:
I'm using built-in network manager HUD and I'm fine with it for now.
But I can't move lobby GUI, only Network Manager HUD. Is there a way to move it down to make space for Title Art?


texts:
Getting started on a 2d platforming project in java. I've decided on using LWJGL and OpenGL, but I don't quite know where to start. What is typically the first thing one would work on with a platforming game?

I've never done any game development before, but I'm hoping this will be good practice and hopefully fun to implement and eventually play.

Thanks


texts: MonoGame 3.4 Content Pipeline Extension missing reference

texts:
I'm pretty new to MonoGame and XNA in general. So was wondering how I could import custom content and make it work on any platform. So I came across Content Pipeline Extensions wanted to do it like the documentation says but i cant find MonoGame.Framework.Content.Pipeline.
So I have multiple questions:

Where is it located?
Is there any other way i can load stuff like map data etc.?
If yes does it work on any platform?

Edit:
I can simply load files without the content pipeline. I didn't expect that to work across all platforms. Thanks to Shiro for clearing this up.


texts: importing animations in Blender, weird rotations/locations

texts:
This is for the Blender 2.6 API.

There are two problems:

1. When I import a single animation frame from my animation file to Blender, all bones look fine.
But when I import multiple (all of the frames), just the first one looks right, seems like newer frames are affected by older ones, so you get slightly off positions/rotations.

This is true when both assigning PoseBone.matrix and PoseBone.matrix_basis.

bone_index = 0

# for each frame:
for frame_index in range(frame_count):
    # for each pose bone: add a key
    for bone_name in bone_names: # "bone_names" - a list of bone names I got earlier
        pose.bones[bone_name].matrix = animation_matrices[frame_index][bone_index] # "animation_matrices" - a nested list of matrices generated from reading a file

        # create the 'keys' for the Action from the poses
        pose.bones[bone_name].keyframe_insert('location', frame = frame_index+1)
        pose.bones[bone_name].keyframe_insert('rotation_euler', frame = frame_index+1)
        pose.bones[bone_name].keyframe_insert('scale', frame = frame_index+1)

        bone_index += 1

    bone_index = 0

Again, it seems like previous frames are affecting latter ones, because if I import a single frame from the middle of the animation, it looks fine.

2. I can't assign armature-space animation matrices read from a file to a skeleton with hierarchy (parenting).

In Blender 2.4 you could just assign them to PoseBone.poseMatrix and bones would deform perfectly whether the bones had a hierarchy or none at all.

In Blender 2.6, there's PoseBone.matrix_basis and PoseBone.matrix. While matrix_basis is relative to parent bone, matrix isn't, the API says it's in object space. So it should have worked, but doesn't. So I guess we need to calculate a local space matrix from our armature-space animation matrices from the files.
So I tried multiplying it ( PoseBone.matrix ) with PoseBone.parent.matrix.inverted() in both possible orders with no luck, still weird deformations.


texts: How do I disable function when triggerExit2D?

texts:
I want to add a system when the player moves to the door, the scene changed but if the player walks away from the door the function that I call disables it. so I put OnTriggerEnter2D and OnTriggerExit2D to make that. The issue is once the triggerExit the bool return false but not the function.
so this my script:
     private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            finish = true;

            if (finish)
                StartCoroutine(WaitForChangeScene());
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            finish = false;
        }
    }

    public IEnumerator WaitForChangeScene()
    {
        yield return new WaitForSeconds(1);
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

    }


texts: I'm developing a race game in Andengine. I have created a car which player is controlling. But since this is a race game, there should be 3 or 4 car which snatch with the player's car. My question is: How do the opponent cars move along the path? How their logic works? Must I know certain path?


texts: Does interleaving in VBOs speed up performance when using VAOs

texts:
You usually get a speed up when you use interleaved VBOs instead of using multiple VBOs. Is this also valid when using VAOs?

Because it's much more convenient to have a VBO for the positions, and one for the normals etc. And you can use one VBO in multiple VAOs.


texts:
I'm confused on how the game's methods are called and when.

So I read that the sequence is:

Initialize
LoadContent
Update
Draw
UnloadContent

Where 3 and 4 are the game loop, so after Update is called, Draw is called, then Update, then Draw, and so on. The game loop (Update and Draw) is executed 60 times per second.

Then I read in another place that Update and Draw can be invoked at different times and Update may be called more then one time before Draw and so on.

... and at the end UnloadContent is invoked after the Update if the Exit method is called.


texts: Collision Detection/Response Issues in Unity

texts:
Sprite A: Box Collider 2D and Rigidbody 2D.

Sprite B: Box Collider 2D.

Both sprites have a Sprites/Default material with Pixel Snap enabled. The textures being used are set to Truecolor Format and Point Filter Mode. No Mip Maps and 1 Pixels Per Unit (higher PPU seems to make the issue more obvious, but lower value does nothing but scale the problem down).

I put Sprite A above Sprite B, hit play. I see Sprite A fall into Sprite B and hover slightly above it. I think this is horrible, so I look it up. I find I can lower Min Penetration For Penalty to help.. but not fix.. this issue. It's barely noticeable now.

After a while, I noticed Sprite A sometimes overlaps Sprite B briefly during collisions. I can't seem to find a clean fix to either of these issues.

Is Unity's physics engine just not designed for the level of accuracy I'm wanting? It seems the whole way the physics engine works is by allowing overlap (minPenetrationForPenalty) before pushing objects out of each other. I've been coding for many years as a hobbyist, so no professional experience, but this seems.. wrong. Are there options that don't involve overlapping of objects?

Thanks for any and all help.


texts:
In C++, how can one make it's game load content developped by other people?

For instance in Java you can look for jar files and load specific class from it.


texts: Slick & NiftyGUI. Nifty initialize exception

texts:
I found my self into trouble when trying to run a Slick game with a Nifty Game State.
This is the code:

@Override
protected void initGameAndGUI(GameContainer container, StateBasedGame game)
        throws SlickException {
    initNifty(container, game);
}

If i run this i get: java.lang.IllegalStateException: The NiftyGUI was already initialized. Its illegal to do so twice.

If i delete the call to initNifty() i get another exception:java.lang.IllegalStateException: NiftyGUI was not initialized.


texts: MYST/RIVEN and Quicktime Video Integration

texts:
How was Quicktime video integrated into the MYST series games? I was watching a Making of MYST video and noticed that they used a small green screen and for the sequels like Riven they continued to use a green screen but with a much bigger stage. How is it that they match up the video file and integrate it seamlessly into the game? I'm really curious as to how they did it with Riven, where full body actors actually move around with a greater degree of freedom.

My guess is that the video recording is an exact duplicate of a pre-rendered scene. When the player enters into a certain area where a movie is supposed to take place, the video is drawn onto the screen and played. After the video ends, the pre-rendered screen is drawn back to the screen that reflects the changes that took place in the video.

Any other ideas how it might have been done?


texts: Physics motor on servers, How a billiard server works?

texts:
i'm trying to figure how a phisics game like billiard works in server side . I'm asking this cause i know how to achieve this in a client , but if i use a phisics motor i think it could be very heavy for a server when i want to have many people in the server.

When i see this type of games, it use to be really fast , thinking that server is controlling the movements of course . Cause any other way maybe from client you could have been doing cheats.

Then my questions are:

The server sends in this case, all ball movements?
Are the server trusting in clients?
In this case : How to be sure a phisics motor doesn't have little error. (float decimals differences)

And globaly : How this type of server works?


texts:
I'm very confused about the SDL2 viewport, I did some googling to find out how to implement it but people keep mentioning things like "world coordinates" which I don't have in my game.

Question : Do I even need world coordinates for the SDL2 viewport to work? If yes, how do I implement it?

I've currently got a problem where if my viewport goes too much to the right or down, the entire window will become green, kinda like if it stopped rendering all my sprites.

Here's a GIF to show you what I mean :

As you can see, whenever I go too much to the right or down the entire screen goes green.

I thought this maybe was beause of me not using world coordinates, but I have no idea I'm just guessing stuff at this point...

My current codes for moving the viewport, drawing it, and such looks like this :

Creating the viewport / camera :

Camera::Camera(Uint16 x, Uint16 y, Uint16 w, Uint16 h)
{

    // Sets up the viewport positions and sizes
    viewport.x = x;
    viewport.y = y;
    viewport.w = w;
    viewport.h = h;

    // Sets the viewport so that SDL uses it
    SDL_RenderSetViewport(Window::GetRenderer(), &viewport);

}

Drawing the viewport : (gets called every frame)

void Camera::DrawCameraViewport()
{
    SDL_RenderSetViewport(Window::GetRenderer(), &viewport);
}

I set the cameras position during runtime like this :

void Camera::SetCameraPosition(int _x, int _y)
{
    viewport.x = _x;
    viewport.y = _y;
}

And here's how I set the cameras position using the above function :

Note : Sorry, the line became giantic...

camera->SetCameraPosition(
    -SpriteManager::GetPlayerSprite()->GetPosition().x
    + Window::GetWindowMiddlePoint().x
    - SpriteManager::GetPlayerSprite()->GetMiddlePoint().x

    , -SpriteManager::GetPlayerSprite()->GetPosition().y
    + Window::GetWindowMiddlePoint().y
    - SpriteManager::GetPlayerSprite()->GetMiddlePoint().y);

Question : Am I implementing the viewport correctly?


texts: Why is Euler integration sometimes preferred over RK4 even if RK4 is more accurate?

texts: Some high quality engines such as Box2d uses the Simplistic Euler integrator instead for RK4 when Eumplectic Euler commits a global error of the order of Δt whereas, RK4 has Δtˆ4 error? RK4 is not that hard to do, right? Why would a physics engine use Euler over RK4 hence sacrificing accuracy ?


texts:
I am making a game which has many balls bouncing around the screen (around 200-300 balls in a small area). One thing I am trying to do is improve the performance of the collision detection and resolution.

What I've tried to do so far is to maintain a large number of ArrayLists. I split the screen up into a grid and for each cell I keep an ArrayList containing each ball that is currently inside that particular grid square. Whenever I update the positions of the balls, I also update which list they belong to.

When checking for collisions, I have a separate ArrayList which contains all the balls. I iterate through this list, and for each ball:

find out what grid square it is in
check for collisions with all the balls in adjacent grid squares

I've tested this approach and it doesn't seem any different to just iterating over a list of all the bubbles twice.

Does anyone have some suggestions on how I can improve things? For instance, with my current algorithm I am handling collisions twice but I'm unsure how I can work around it.


texts: Responsibility of rendering in a component/entity game engine

texts:
I am developing a simple component/entity game engine in C# (https://github.com/alexvm/BlueShift) and have a few questions regarding the responsibility of certain items in the engine itself. I have the following:

Scene
Entity
Component

I am planning to have the scene maintain a collection of entities. To draw components on screen, the scene will loop over entities draw any components that extend from a drawable parent.

E.g. a drawable component might look like:

public class SpriteComponent : Drawable {

}

And in as scene I would call:

foreach(var entity in entities) {
    Scene.DrawComponents(entity.DrawableComponents());
}

Does the responsibility of each class make sense? I.e. does it seem like good design for the scene to maintain all entities and for the entity to present the drawable components to the scene to draw?


texts: How can I resize pixel art in Pyglet without making it blurry?

texts:
I have a tileset of 8x8 pixel images, and I want to resize them in my game so they'd be double that (16x16 pixels, e.g. turning each pixel into a 2x2 block.) What I'm trying to achieve is a Minecraft-like effect, where you have small pixel images scale to larger blockier pixels.

In Pyglet, the sprite's scale property blurs the pixels. Is there some other way?

Working Code:

Here's the solution that works (thanks to DMan's persistence and Jimmy's insight):

image = resource.image('tileset.png')
texture = image.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
texture.width = 16 # resize from 8x8 to 16x16
texture.height = 16
texture.blit(100, 30) # draw


texts: Trying to trigger dialogue when the space bar is clicked, and two objects are colliding

texts:
I'm getting a NullReferenceException on OnTriggerStay. I've been going crazy trying to figure out why. I have tried to cut this down to only the relevent information. I got this code through a tutorial: https://www.youtube.com/watch?time_continue=48&v=_nRzoTzeyxU (just for credits).

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

[RequireComponent(typeof(Rigidbody))]
public class MainCharacter : MonoBehaviour {
    public int limbs;

    public float speed;
    public Vector3 jump;
    public float jumpForce;
    Rigidbody2D rb;
    public float fire_start_time = Time.time;
    Animator animator;
    public DialogueManager dialogueManager;

    // Checking if we are grounded
    public bool isGrounded;
    public LayerMask groundLayers;

    private SpriteRenderer myRenderer;

    public Sprite[] LimbSprites;

    void Start()
    {
        dialogueManager = gameObject.GetComponent<DialogueManager>();
    }

    public void OnTriggerStay2D(Collider2D collision)
    {
        if (Input.GetKey(KeyCode.Space))
        {
            Dialogue dialogue = collision.GetComponent<Dialogue>();
            dialogueManager.StartDialogue(dialogue);

        }
    }

}

Here is my dialogue manager:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DialogueManager : MonoBehaviour {

    public Text nameText;
    public Text dialogueText;

    public Animator animator;

    private Queue<string> sentences;

    // Use this for initialization
    void Start () {
        sentences = new Queue<string>();
    }

    public void StartDialogue (Dialogue dialogue) {

        animator.SetBool("IsOpen", true);

        nameText.text = dialogue.name;
        sentences.Clear();

        foreach (string sentence in dialogue.sentences) {
            sentences.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence() {
        if (sentences.Count == 0) {
            EndDialogue();
            return;
        }

        string sentence = sentences.Dequeue();
        dialogueText.text = sentence;
    }

    void EndDialogue() {
        animator.SetBool("IsOpen", false);
    }
}

Here is DialogueTrigger

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

public class DialogueTrigger : MonoBehaviour {

    public Dialogue dialogue;

    public void TriggerDialogue () {
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);

    }
}

Here is Dialogue

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

[System.Serializable]
public class Dialogue : MonoBehaviour {

    public string name;

    [TextArea(3, 10)]
    public string[] sentences;

}


texts:
Drawing multi-colored text or highlighted text in XNA/MonoGame is pretty annoying, and the standard way I've seen to do it is to just to make multiple SpriteBatch.DrawString calls, and place them using the x-coordinates given by SpriteFont.MeasureString. This is fine if you're highlighting whole words or blocks of text, but if you only want to highlight select letters inside of a word, you get a kerning nightmare:

Sometimes this looks alright, but not consistently and I can't think or find a good way to space out the letters properly.

Therefore, I would like to know if there's either a better way to draw highlighted text like this in XNA/MonoGame, or a way to pull kerning data out of a font so I can space the letters properly or some other fancy way to do it using masks or whatnot.

Thanks in advance!


texts: How calculate a new node after cutting a node into an octree

texts:
I'm working on a small XNA game, voxel-based like minecraft.
I've recently faced a problem in how to delete a node (cube) from an octree and re-calculate the new octree afterward.

I have already tried searching for implementations of the algorithm on the net, but without success.

This is the function I tried:

    /* ****************** */
    /* RemoveCubeFromNode */
    /* ****************** */
    #region RemoveCubeFromNode
    // Remove a node from an Octree
    private BoundingBox[] RemoveCubeFromNode(BoundingBox cubeToDelete, BoundingBox cubeParent )
    {
        // ......
        // split the cube from parent
        // return the two new BoundingBoxes
    }
    #endregion

Here are the pictures that represent what should be my functionality:
Knowing that my function should always return 2 new cubes (boundingBox) or 1 only.

In red is the cube to remove

In brown and blue are the two new cubes calculated

A thousand thanks in advance to whoever can help me... this algorithm is driving me crazy, and I can not stop thinking that someone else must have had this problem too.

The way about how i calculate my octree from my world

First I initialize an integer array with 3 dimensions.
Where each integer value corresponds to a structure id.
0 - no structure (empty)
1 - land
2 - [water]  etc ...
`

public void generateMatriceWorld()
{
     int[][][] matrice = null;
     int widthMap = 1024; int lengthMap = 1024; int heightMap = 64;
     matrice = new int[widthMap][][];
     for (int i = 0; i < widthMap; i++)
     {
        matrice[i] = new int[lengthMap][];
        for (int j = 0; j < lengthMap; j++)
        {
          matrice[i][j] = new int[heightMap];
        }
     }

     //randoom put value Inside my world

`

After that i use the method where I divide my world => 8 blocks by 8 blocks  if more than one floor, and 4 if one floor. And this until the blocks structure curently cutted get the same structure .


texts: Using fully cropped sprites with TexturePacker and Cocos2d

texts:
When using texturepacker, you can set your trim-mode to crop. This is nice, because when a sprite loads in cocos2d your bounding box will only be the visible area of your sprite - which is useful for things like collision detection etc.

However, if you have a complex animation - say a warrior with a sword, there is a good chance that the visible rect of your sprite is changing with each frame. For example, when the sword swings backwards or forwards your sprite width would adjust.

Cocos2d seems to handle this in a less then ideal way - when the dimensions change the sprite seems to dance around, rather then anchoring to centered point. In an engine I wrote, I handled this by using a set anchor point and direction for an animation. So if an animation got wider you could make sure it extended in a given direction (for example, a punch would extend in one direction, rather then appear to push the sprite backward from the fist)

Does cocos2d have any mechanism for handling this? I looked at anchorpoint, but it doesn't seem to handle this scenario.


texts: How is the Call of Duty checkpoint system implemented?

texts:
Does anybody know how it is implemented or has any advice how to do it?

I'm especially interested in how to avoid that a player dies right after a checkpoint. How does the game evaluate when it's save to do one. Of course there seem to be "simple" triggers based on passing through a position in the map or achieving certain objectives, but I'm pretty sure they avoid that the game saves while a bullet is in flight killing you.

I have the feeling that the game shows you something slightly different on every reload, like if it would save the game at one point and maybe do a little replay. If it reloads and you die quickly, the next reload will be slightly different, I feel.

Could it be that once a trigger for a checkpoint is passed, the game saves it's whole state to a new file. Then it waits for maybe 2s whether you die. Only if you don't die it saves the game. Is that all?

Maybe it even freezes it's random number generator and stores the next player actions, too. So when the checkpoint loads, it can fast forward a little bit and a different amount of time each load?


texts:
I have weird glitch in my game. When player shoot the gun, bullet is instantiated something called "ShootPoint" transform.

This is the ShootPoint's position:

And this is the code of firing bullet:

RigidbodyProjectile CreateBullet() {
    GameObject bullet = Instantiate(bulletPrefab, shootPoint.position, shootPoint.rotation);
    RigidbodyProjectile projectile = bullet.GetComponent<RigidbodyProjectile>();

    projectile.rigidbody.AddForce(shootPoint.forward.normalized * bulletSpeed, ForceMode.VelocityChange);

    return projectile;
}

Simple script to just instantiate bullet prefab in ShootPoint.transform.

However when I run the game, bullet generated totally wrong place:

That picture captured right after creation, even before push the bullet. Here's the updated code for capture that moment, I intentionally throw the error so that makes game stop:

RigidbodyProjectile CreateBullet() {
    GameObject bullet = Instantiate(PrefabManager.GetPrefab("bullet"), shootPoint.position, shootPoint.rotation);

    // Throw the exception
    throw new System.Exception("DIE");

    // So codes under here will not work
    RigidbodyProjectile projectile = bullet.GetComponent<RigidbodyProjectile>();

    projectile.rigidbody.AddForce(shootPoint.forward.normalized * bulletSpeed, ForceMode.VelocityChange);

    return projectile;
}

I don't get it, why my bullet doesn't generated in ShootPoint.transform? I literally removed all components in Bullet and tried again but still had same problem.

Funny thing is that this is not always happening, it only happens in certain angles, especially looking down. I already checked hundreds that ShootPoint pointing something wrong direction or reference of ShootPoint was wrong, but no, there was no problem at all!

What should I check in this case? It's really annoying issue, because when I shoot little lower angle, it always hit the ground almost instantly after fire.

Anyone who knows about this issue, if could be great what should I check, thanks.

** Additional Info about Bullet **
I forgot to mention about bullet. It has parent and child, and parent has rigidbody and child has mesh to display. This is because basically bullet wasn't pointing forward so I rotated it to pointing forward and wrapped by empty game object so that eventually it pointing forward direction even mesh is rotated.

Here's the screenshot to explain this:


texts: How to define a proper protocol for a turn-based combat system?

texts:
I'm working on the server side of a turn-based strategy game. The game has a really complex combat system, like:

  When you are hit, you summon a phoenix to attack the enemy that deals X damage, and the phoenix fly back to heal Y of your health.

Well, such skill does sounds interesting, but requires a great amount of work on the skill and combat system.

We did not use script on the server. We just split one skill into several skill effects. For instance, we have DamageEffect, AddBuffEffect and so on. However, we have a lot of skills like the phoenix stuff above, they can be triggered at a specific moment. And some of them even replace the main attack skill. So we designed several SkillConditions for that. It worked, although not very well.

However, the question is: For such a complex combat system, how to define the protocol between client and server?

For example:

  A attacks B using skill X for 30 damage points. B uses the phoenix skill Y when he is hit that damage A for 20 points, and heals himself 10 points.

How can we express this to the client? We currently use a structure like this:

useSkillAction:
    skill: id_of_X
    source: id_of_A
    target: id_of_B
    subActions:
        damageAction:
            timing: onHit  // Timing means the the damageAction will trigger when the skill animation triggers a 'hit' event.
            character: id_of_B
            damage: 30
            subActions:
                propertyChangedAction:
                    timing: onFinished
                    character: id_of_B
                    property: health
                    value: health_of_B
                useSkillAction:
                    timing: onFinished
                    skill: id_of_Y
                    source: id_of_B
                    target: id_of_A
                    subActions:
                        damageAction:
                            timing: onHit
                            character: id_of_A
                            damage: 20
                            subActions:
                                propertyChangedAction:
                                    timing: onFinished
                                    character: id_of_A
                                    property: health
                                    value: health_of_A
                        healAction:
                            timing: onFlyBack??
                            character: id_of_B
                            damage: 10
                            subActions:
                                propertyChangedAction:
                                    timing: onFinished
                                    character: id_of_B
                                    property: health
                                    value: health_of_B

Well, I think you got the idea. For now, this structure can handle only simple skills. The solution currently have three problems:

For complex skills, like above, it's hard to describe the timing of phoenix fly back.
For the onHit timing in damageAction, that means the server even knows that there's an animation trigger called 'hit'.
It's hard to maintain.

Is there a better way to do this? Thanks anyway, for my broken English...

EDIT: As Petr suggested, I reduced the question to a simpler one:

Is there a way to define the protocol so that server does not care about animation trigger stuffs like 'onHit'? Because, generally speaking, server should only care about the logic.


texts: Bad Viewports Using Unity with Google Cardboard VR on iOS

texts:
I'm using unity 2017.3.1f1, building for an iPhone SE.

I'm able to build the google HelloVR scene, available from the Google Cardboard VR unity package. However, in the end result, the cameras are giving the wrong display. They aren't lined up to create stereoscopic vision at all, and the image appears distorted.

Here is an example of the output: https://i.imgur.com/Y4pqdiy.jpg

Is there a default setting in the Google Cardboard VR package that can be changed to fix this?


texts: Is there a practical reason for saving game data in %UserProfile%\Documents instead of %AppData%?

texts:
My documents folder is flooded with subfolders of various games, including those of some very recent AAA titles.
As a professional application developer with no experience in the gaming industry this is just plain wrong, these files belong into %APPDATA% or %LOCALAPDATA%.

My question is, is there a conscious decision to put these files in %UserProfile%\Documents to gain some specific benefits, or is this just legacy behavior that carried over from the days of Windows XP? Or is there an even better reason like, e.g. Steam requiring or recommending this, or a popular engine doing this by default?

Related: In which directory to write game save files/data? (to avoid pointless discussions)


texts: How can I assign disabled Text ui to array in the Inspector?

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

public class BlendShapesController : MonoBehaviour
{
    public Text[] texts;
    public bool startTalking = false;
    public float talkTime;
    public float duration;
    [Range(0, 100)]
    public float valueRange;
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool isTalking = true;

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
    }

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

        if (startTalking && isTalking)
        {
            StartCoroutine(AnimateMouth());
            StartCoroutine(TalkTime());

            isTalking = false;
        }

        if (startTalking == false && isTalking == false)
        {
            isTalking = true;
        }
    }

    //Lerp between startValue and endValue over 'duration' seconds
    private IEnumerator LerpShape(float startValue, float endValue, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
            bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
            yield return null;
        }
    }

    //animate open and closed, then repeat
    public IEnumerator AnimateMouth()
    {
        while (startTalking == true)
        {
            yield return StartCoroutine(LerpShape(0, valueRange, duration));
            yield return StartCoroutine(LerpShape(valueRange, 0, duration));
        }
    }

    public IEnumerator TalkTime()
    {
        yield return new WaitForSeconds(talkTime);

        startTalking = false;
    }

    public void StartTalking()
    {
        for (int i = 0; i < texts.Length; i++)
        {
            if (texts[i].text != "")
            {
                startTalking = true;
            }
        }
    }
}

I want that if one of the ui texts is not empty and not disabled to start talking by calling the StartTalking method. The game start when all the ui texts are disabled one of them is not empty but they are all disabled. And during the game they are turning disabled enabled in the game and get empty not empty.  On the ui text is not empty.
The problem is in the Inspector I can't drag disabled ui texts to the array of the script.
All the ui texts are childs under their own parents that are childs of the prefab name Game UI Texts.

This are the ui texts in the screenshot that should be dragged to the sccript on the right in the Inspector :
Scene Text , Description Text , and Long Distance Description Text
The main goal is to use one script to control automatic the talking with the text in the game.
When there is a text in the game on the screen StartTalking and stop talking when there is no text on the screen.


texts: Unintended sliding blocks Unity (5) physics

texts:
A game I'm working on right now relies on the Unity physics system for collisions, gravity etc. This all works well except for one strange thing. When an explosive is placed on a stone cube, it'll slide right off.

A video displaying the sliding behavior: https://www.dropbox.com/s/lr6lhnn30x61tvf/Unity%202015-02-19%2013-41-39-54.avi?dl=0

The stone gameobject settings: http://puu.sh/g3BFn/c15483b8ea.jpg The explosive has the same settings except for that the Mass is 1.

What could cause this weird sliding and how can it be fixed?


texts:
I was wondering if this is a possibility with RTMFP since it acts like UDP/P2P..

Host Migration

Player A starts and host a game..
Player B and C connects..
Player A quits..
Player B is now assigned as new host/server
Game not interrupted or disconnected.

Maybe some basic example on how this is done with RTMFP/AS3?


texts:
I want my game to start after a "3-2-1 go" countdown.

My Player Script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour {

    private Rigidbody2D myRigidbody;

    private Animator myAnimator;
    private int skor;
    public Text toplamSkor;
    public Text highScore;

    [SerializeField]
    private float hiz;
    private bool sagaBak;

    [SerializeField]
    private AudioSource altinSes;

    // Use this for initialization
    void Start () {
        sagaBak = true;
        skor = 0;
        highScore.text = PlayerPrefs.GetInt ("HighScore", 0).ToString();

        myRigidbody = GetComponent<Rigidbody2D> ();
        myAnimator = GetComponent<Animator> ();

    }

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

        float yatay = Input.GetAxis ("Horizontal");
        TemelHareketler (yatay);
        YonCevir (yatay);

    }

    private void TemelHareketler (float yatay){
        myRigidbody.velocity = new Vector2 (yatay *hiz, myRigidbody.velocity.y);
        myAnimator.SetFloat ("KarakterHizi", Mathf.Abs (yatay));

    }
    private void YonCevir (float yatay)
    {

        if (yatay > 0 && !sagaBak || yatay < 0 && sagaBak) {

            sagaBak = !sagaBak;
            Vector3 yon = transform.localScale;
            yon.x *= -1;

            transform.localScale = yon;
        }
    }
    void OnCollisionEnter2D(Collision2D other) {

        if (other.gameObject.tag == "altin") {
            other.gameObject.SetActive (false);
            altinSes.Play ();
            skor = skor + 1;
            SkorAyarla (skor);

            if (skor > PlayerPrefs.GetInt ("HighScore", 0))
            {

                PlayerPrefs.SetInt ("HighScore", skor);
                highScore.text = skor.ToString();

            }
        }
}
    void SkorAyarla(int count)
    {
        toplamSkor.text = count.ToString ();
    }

    public void Reset (){
        PlayerPrefs.DeleteAll ();

    }
}


texts: How to prevent rendered wound from sliding on moving character?

texts:
I am trying to display a rendered wound on the character, but I still can't figure out how to display it properly without sliding on character's body.

I'm following this link on rendering the wounds on characters but I still can't figure out why it isn't working.

This is what I have so far on rendering the wound based on hit location

What have I done wrong? Any ideas is appreciated. Thanks!

p.s This is how I draw the wound based on hit location.

UPDATE:
So I replace WorldPosition into Preskinned Position based on the comment suggested and the sphere mask won't render at all. I thought my HitLocation must be the problem, so I get back to the linked post to understands better on how to approach this, and included some C++ as well, but all those still resulting in the same results. The sphere mask keep on sliding on the body.

This is the code I have been using for both callable functions above

//Recursive function to have results relative to world origin
FTransform UGestureMathLibrary::GetWorldSpaceTransform(FReferenceSkeleton RefSkel, int32 BoneIdx)
{
 FTransform BoneTransform;

 if (BoneIdx > 0)
 {
  BoneTransform = RefSkel.GetRefBonePose()[BoneIdx];

  FMeshBoneInfo BoneInfo = RefSkel.GetRefBoneInfo()[BoneIdx];
  if (BoneInfo.ParentIndex != 0)
  {
   BoneTransform *= GetWorldSpaceTransform(RefSkel, BoneInfo.ParentIndex);
   UE_LOG(LogTemp, Warning, TEXT("if parent index is not equal to zero"));
  }
 }

 return BoneTransform;
}

//Reference pose bone transform
FTransform UGestureMathLibrary::GetRefPoseBoneTransform(USkeletalMeshComponent* SkelMesh, FName BoneName)
{
 FTransform BoneTransform;

 if (SkelMesh && !BoneName.IsNone())
 {
  SkelMesh->ClearRefPoseOverride();
  FReferenceSkeleton RefSkel;
  RefSkel = SkelMesh->SkeletalMesh->RefSkeleton;
  BoneTransform = GetWorldSpaceTransform(RefSkel, RefSkel.FindBoneIndex(BoneName));
  //BoneTransform = RefSkel.GetRefBonePose()[RefSkel.FindBoneIndex(BoneName)];
 }

 return BoneTransform;
}

//Bone transform
FTransform UGestureMathLibrary::GetBoneTransform(USkeletalMeshComponent* SkelMesh, FName BoneName)
{
 FTransform BoneTransform;

 if (SkelMesh && !BoneName.IsNone())
 {
  FReferenceSkeleton RefSkel;
  RefSkel = SkelMesh->SkeletalMesh->RefSkeleton;
  BoneTransform = SkelMesh->GetBoneTransform(RefSkel.FindBoneIndex(BoneName));
 }

 return BoneTransform;
}

Am I missing something?? Thanks again!


texts: What is a good book to start programming a 2D C++ game?

texts:
I have a degree in Computer Science and while I was in college, I created a simple 2D game in Game Maker.  I would like to recreate this game in C++ as a start to learning how to create games in C++.  What would be a good book to start out on programming games in C++ for someone who has a bit of C++ experience (My CS Major classes were taught using Java and I had a class in C++ to learn syntax) and knowing the concepts behind objects, methods, inheritance, etc?

This would be a hobby of mine while I build up experience until I one day could work in the Vide Game Industry.


texts: Reasons to disable game save during combat (e.g. Mass Effect 2)

texts:
So I've been playing Mass Effect 2 (PC) and one of the things I've noticed is that you can only save your game when you're not engaged in combat.  As soon as the first enemy shows up on your radar, the save button is disabled.  Once combat is over, save functionality reappears.

It seems reasonable to assume that Mass Effect 2 is a state machine, and therefore, the internal state of the program at any moment can be captured and reloaded later.  This is basically a solved problem - games have been designed this way since the Half-Life era.  It also seems reasonable to assume that BioWare knew what they were doing when they made the decision not to follow this model - it's a tried and true system; BioWare wouldn't have done it the way they did without some good reason.

What reasons are there to disable game save functionality during combat?


texts: From articles on the web, I found that floating point math generally has accuracy of at least 6 digits. With this in mind, is it possible to make Box2D which uses floats fully deterministic through the use of heavy rounding (i.e. 1st or 2nd decimal place)?


texts:
I'm working on a 4x, turn-based space game.  It's currently in the design phase.  Because I'm the Director of Technology for Gamers Against Bigotry, I'd like it to be socially conscious.  In other words:  I want the game to have features that encourage socially aware gameplay.

I've had some ideas.  The first is that some worlds will have aboriginal peoples.  Second, there will be some smaller empires (much like City-States in Civ 5) that don't colonize more than one or two systems.

In a normal 4x game, there is absolutely no penalty for attacking these civilizations, or for destroying aboriginals (their might be expensive military costs, but that's it.)

One idea I had was to set up a council of Elder Races who could punish players who interfere with Aboriginal Cultures. I also thought about using Factions that have to be appeased, and these factions could interfere with the player's ability to procede (for example, Human Justice factions would strike if the player hurt aboriginal peoples.  Environmental factions might strike or destroy buildings that hurt native fauna/flora.)

Finally, I thought about allowing the player to choose their sexual identity (Male, Female, Trans*, etc).

Does anybody have any other ideas to make the game more socially conscious?  Obviously, gameplay should still be fun. I just want the players to think about their actions in a greater social context.


texts: Is it legal to use elements of the outfit of a character in another game as an optional cosmetic in my own game?

texts:
In my game, I plan on implementing various optional unlockable costumes, earned by collecting in-game items.  One hypothetical example of such a costume would be Banjo's (from Banjo-Kazooie) shorts, backpack, and shark-tooth necklace.  In trying to find the answer to this, I've found plenty of information about directly using Banjo himself (clearly illegal without a license), but I haven't found any form of direct answer when it comes to his outfit placed onto the main character.

The closest thing I've found to an answer are similar cosmetics being used in other games -- In TF2, for example, there's a hat that references Mario's hat, but replaces the M with an E, while in Terraria, there's a direct recreation of Mario's entire outfit.  Obviously, though, just because another company was able to do such a thing doesn't mean I necessarily will be able to as well.

Lastly, I'm not sure if it makes much of a difference, but it's also worth mentioning that the art assets used for these costumes would be entirely created by me in the image/likeness of the other characters' outfits -- obviously, ripping said assets from the games themselves would NOT be legal.  Also, I do plan on selling the game and making a profit on it.

Would creating these homage outfits be legal, or would it violate the copyright and/or trademark (not sure which applies) of the character?


texts: How do i make player input object spawning data driven?

texts:
I'm using component based design and am at the stage or re-factoring simple player input to be data driven.

Currently i have a PlayerControlComponent, which an entity has if it should be player controlled. Currently only a single entity has this.

I have an InputSystem that acts on entities with PlayerControlComponent, PhysicalComponent and MoveableComponent components.

Below is the code that actually does the entity creation:

if (_InputActionManager.IsAction(_ActionFireBullet))
{
    if (WorldManager.CanDoAction(playerControlComponent.CreateBulletActionId))
    {
        // Create a bullet and fire it
        using (var entityTemplate = WorldManager.GetEntityTemplate(@"EntityTemplates\Bullet"))
        {
            var bulletPhysicalComponent = entityTemplate.Item.GetComponentOfType<PhysicalComponent>();
            var bulletMoveableComponent = entityTemplate.Item.GetComponentOfType<MoveableComponent>();

            bulletPhysicalComponent.Position = physicalComponent.Position + physicalComponent.Direction * physicalComponent.Radius;
            bulletPhysicalComponent.Direction = physicalComponent.Direction;
            bulletMoveableComponent.Velocity = moveableComponent.Velocity + physicalComponent.Direction * 200;
        }

        WorldManager.MarkActionDone(playerControlComponent.CreateBulletActionId);
    }
}

I want to get to the stage where I can have an XML file that indicates some how that a given entity will create a new entity based on a given template and set initial values such as position, direction and velocity in the above example.

I want to avoid having to change code and maybe add systems and components for each type of thing I want to spawn.

For example, currently if I wanted to add the ability for an enemy to spawn a missile I'd need to define my missle entity template (fine), create a new component to mark the entity as being able to fire a missle, then create a system that uses that component (want to avoid), then create a system with code similar to the above (want to avoid).

As another example, say I want to change the speed of the bullet, currently I do that in code, but I want to be able to do that in a data-driven way.

How can I create and manage a way of creating an entity based on an event occuring, with properties based on the entity that created it? i.e. Player presses Fire, bullet spawned at ship location, moving away from ship.


texts: I've just started developing my first game with android using SurfaceView. I scale my bitmaps to support different screen sizes. But I don't know it's better to do the scaling when loading the bitmaps or when drawing them to canvas using Matrix. I guess the first one would occupy more memory but it's better in performance. But I don't know how really things work here so any suggestion from experts would be appreciated.


texts: How to implement a camera for a TiledMap with SDL2 and Box2d?

texts:
I m writing a game engine using mainly SDL2 and box2D,
I implemented TiledMap class that loads a tmx map and everything is fine it even support animation and objects that later will generate Box2D bodies for collision

Everything is fine till Camera came in I implemented camera class and its working fine for the sprites and the map but something is annoying me the bodies that get generated will stay at their position when the camera moves!

To illustrate the problem see these screenshots:

Without moving the camera the result is normal:

I tried to come up with some solution one of them is to translate all of the map bodies backward. The solution honestly worked but have some side effects that made me not satisfied at all with the result

Expensive (specially if your setting the camera every frame)
Results in a non physical behavior !

Finally I will show some code so the reader will understand exactly what Im doing:

Camera Class:

void Camera::addObjectToCamera(TiledMap* map)
{
    m_CameraAttachedObjects.emplace_back(map);
}

void Camera::moveCamera(Vec2i p_Offset)
{
    m_CamPos += p_Offset;
    for (auto& obj : m_CameraAttachedObjects)
    {
        p_Offset.x = -p_Offset.x;
        obj->translateMap(p_Offset);
    }
}

void Camera::setCameraPosition(Vec2i p_Pos)
{
    m_CamPos = p_Pos;
    for (auto& obj : m_CameraAttachedObjects)
    {
        obj->setPosition(p_Pos);
    }
}

TiledMap class:

void TiledMap::render(float dt)
{
    SDL_RenderCopy(r, m_MapTexture, &m_MapSrc, NULL);
}

void TiledMap::setPosition(Vec2i pos)
{
    static Vec2i LastPositionTranslated = Vec2i(0, 0);
    if (Utility::IsInBox(Vec2i(pos.x, pos.y), Vec2i(0,0), Vec2i(m_MapDst.w, m_MapDst.h))) {
        m_Position = pos;
        m_MapSrc.x = pos.x;
        m_MapSrc.y = pos.y;
        for (auto& itr : m_cachedAnimatiedTiles) {
            auto current_rect = itr->tiledLayerData->DestDraw;
            itr->tiledLayerData->DestDraw->x = current_rect->x - (pos.x - LastPositionTranslated.x);
            itr->tiledLayerData->DestDraw->y = current_rect->y - (pos.y - LastPositionTranslated.y);
        }
        for (auto& phyObj : m_allMapBodies) {
            Vec2f old_transform = phyObj->GetTransform().p;
            phyObj->SetTransform
            (
                Vec2f(old_transform.x-float(pos.x - LastPositionTranslated.x), old_transform.y-float(pos.y - LastPositionTranslated.y))
                ,0.f
            );
        }
        LastPositionTranslated = pos;
    }
}

void TiledMap::translateMap(Vec2i pos)
{
    if (Utility::IsInBox(Vec2i(m_MapSrc.x - pos.x, m_MapSrc.y - pos.y), Vec2i(0, 0), Vec2i(m_MapDst.w, m_MapDst.h))) {
        m_Position += pos;
        m_MapSrc.x -= pos.x;
        m_MapSrc.y -= pos.y;
        for (auto& itr : m_cachedAnimatiedTiles) {
            auto current_rect = itr->tiledLayerData->DestDraw;
            itr->tiledLayerData->DestDraw->x = current_rect->x + pos.x;
            itr->tiledLayerData->DestDraw->y = current_rect->y + pos.y;
        }
        for (auto& phyObj : m_allMapBodies) {
            Vec2f old_transform = phyObj->GetTransform().p;
            phyObj->SetTransform(old_transform + Vec2f((float)(pos.x), (float)(pos.y)), 0.f);
        }
    }
}

Game class (game manager):

            body->SetLinearVelocity(Vec2f(20.f, body->GetLinearVelocity().y));
        cam->moveCamera(Vec2i(10, 0));

the current code is translating the bodies too which is i consider a bad solution of my initial problem anyone have better solution to scroll in box2d? (See another part of the box2d world)

I aiming later (after fixing this problem) to position the camera to follow my player.

Note: I know my camera is kinda fake and its just change which part of the map texture to draw but there is no other way to do it .


texts:
I am totally new for this setup. I am trying to implement google Leaderboard. I followed the step by step process showed in "This Link". i opened windows -> Google play games -> setup -> Android setup. In Android setup i named the class name and copy and paste the xml code from play store account

This Picture Shows this

then i  clicked setup button. i got two popup boxes, Shows below,

in console i got messages

Note: All my software's are updated version only. first i used jdk 64bit. now i uninstalled 64bit and i installed jdk 32 bit. still i got the same problem

Anybody Please help.

Edit 2:
   using This video now i fixed the error JAVA_HOME not set.

then in unity i tried to do the same. Now it displays another message shown below


texts:
I'm trying to use Unity's 2017 tilemap features. What I would like to do is push a tile's sprite up (change its offset), so that the sprite moves up pixel by pixel and the top of the sprite loops (wraps) back around to the bottom. Basically, I want to animate my "Water" sprite without having to build 20 different versions of the sprite to achieve the same effect.  I was able to do this in Rotorz tiles by accessing its Atlas' MainTexture Offset or something like that but this product is discontinued.  This animation is similar to the water in classic RPG games like Ultima 4.

More than that, I would just love to have runtime access to the tiles to do other things: change out the entire sprite on a single tile, change the color, etc.

I have made a custom Tile class using this example:
https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles-Example.html

But this only seems to affect tiles at the time of placement.

Is this possible and does anyone have a good example?  Docs on this feature are scarce.


texts: animationClip.SampleAnimation() does not result in visible changes

texts:
Here is the relevant code snippet:

public class AnimatedGameObject : MonoBehaviour
{
    private float extentPlayed;

    public AnimationClip Clip;
    public GameObject AnimationTarget;

    private void Update()
    {
        if (this.extentPlayed >= 1f)
        {
            return;
        }

        Debug.Log(this.extentPlayed);

        this.Clip.SampleAnimation(this.AnimationTarget, extentPlayed * this.Clip.length);
        this.extentPlayed += 0.005f;
    }
}

In the Unity Editor, the game object assigned to AnimationTarget contains the animator component controlled by the controller that uses Clip.

However, when I start the game, even though I can see that this.extentPlayed is being incremented every frame, no animation is taking place that I can see.

I am aware that what I am currently trying to do in the Update() method can be achieved by calling SetBool(string name, bool value) on the animator, but the purpose of writing the Update() method this way is to gain familiarity with how the SampleAnimation() method works, so that I can perform more complicated manipulations when necessary.

What changes should I make for the animation to take place?


texts: LibGDX - Viewport unproject is not working

texts:
I develop a small Idle-Clicker Indie-Game but ran into a little problem.

I have a Toast in the middle of the Screen, when the Toast is clicked, there should be a number flying up at the position of the click. And there's the problem!

You see at the picture where I clicked with the mouse and where the number appears.

I already tried a lot of methods to unproject the touch coordinates to world coordinates.

Already tried:

viewport.unproject(vec3);
viewport.unproject(vec2);
stage.screenToSTageCoordinates(vec2);
cam.unproject(vec3)
cam.unproject(vec3, viewportX, viewportY, viewportWidth, viewportHeight)
All of this methods result in the same position of the text like using none of these.

Here is the Code-Snippet where the Cam, SpriteBatch and Viewport gets created:

this.camera = new OrthographicCamera();
    if (Gdx.app.getType().equals(Application.ApplicationType.WebGL)) {
        viewPortWidth = 1280;
        viewportHeight = 720;
    } else {
        viewPortWidth = 540;
        viewportHeight = 960;
    }
    this.viewPort = new StretchViewport(viewPortWidth, viewportHeight, this.camera);
    this.camera.position.set(viewPortWidth / 2F, viewportHeight / 2F, 0F);
    this.stage = new Stage(this.viewPort);
    this.spriteBatch = new SpriteBatch();
    //Update batches
    this.camera.update();
    this.spriteBatch.setProjectionMatrix(this.camera.combined);

Here is the screen render method which renders the Game-Components:

preRender(delta);
    this.spriteBatch.begin();
    renderGameComponents();
    if (ToastCase.toastCase.getCurrentPushMessage() != null) {
        ToastCase.toastCase.getCurrentPushMessage().render(delta);
    }
    this.spriteBatch.end();
    this.stage.act(delta);
    this.stage.draw();
    postRender(delta);

Here is the code where I want to convert the screen coordinates of a click (Stage Button):

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            Gdx.app.error("BASE", "X="+x+" Y="+y);
            Vector3 convertedVectorA = new Vector3(x, y, 0.0F);
            convertedVectorA = ToastCase.toastCase.getCurrentScreen().getViewPort().unproject(convertedVectorA);
            Gdx.app.error("UNPROJECTED", "X="+convertedVectorA.x+" Y="+convertedVectorA.y);
            ToastClickerComponent.this.clickEffectVisualizationManager.addEffectVisualizer(convertedVectorA, ToastCase.toastCase.getPreferenceHandler().getGameData().getToastsPerClick());
            ToastCase.toastCase.getPreferenceHandler().getGameData().setToasts(ToastCase.toastCase.getPreferenceHandler().getGameData().getToasts() + ToastCase.toastCase.getPreferenceHandler().getGameData().getToastsPerClick());
            if (ToastCase.toastCase.getPreferenceHandler().getGameData().isEnableSound()) {
                clickSound.play(1.0F, MathUtils.random(0.5F, 1.0F), 0F);
            }
            collectorButton.setSize(btnSize + 10, btnSize + 10);
            return true;
        }

And the method which renders the ClickEffectVisualizers:

public void render(float delta){
    updateVisualizers();
    removeFinishedVisualizers();
    for (ClickEffectVisualizer clickEffectVisualizer : this.clickEffectVisualizers) {
        this.visualizerFont.setColor(1F, 1F, 1F, clickEffectVisualizer.getOpacity());
        this.visualizerFont.draw(this.batch, clickEffectVisualizer.getAmount(), clickEffectVisualizer.getCenter().x - clickEffectVisualizer.getTextWidth() / 2, clickEffectVisualizer.getCenter().y + clickEffectVisualizer.getCurrentYIndicator());
    }
}

I hope thats enough Informations to help me, if you need more, I will post it.

Regards,
PlayerForce


texts: Distinguish between HTC Vive controller grip buttons in Unity

texts:
In Unity, I can check for grip button presses via the SteamVR API like so:

if(controller.GetPressDown(SteamVR_Controller.ButtonMask.Grip)) { ... }

This results in either true or false so I can only check if any grip button was pressed but not specifically which one.

For Unity's Input API the documentation states [1]:

  The grip trigger differs between platforms:

  The HTC Vive controllers each have two grip buttons but both map to
  the same axis. The value for these buttons is 0.0 when not pressed and
  1.0 when pressed (intermediate values between 0.0 and 1.0 are not possible).

Source: https://docs.unity3d.com/Manual/OpenVRControllers.html

In this case it is again not possible to differ between the two grip buttons.

Is there any way in Unity to check which one of the grip buttons of a HTC Vive controller is pressed?


texts: Managing draw calls for customized materials when targeting mobile

texts:
I want to know how to minimize draw calls when rendering multiple customized characters onscreen, presumably with 3-4 materials apiece. Is there a better way to achieve custom color configurations than instancing/duplicating materials? Am I overthinking the problem?

Our game is a frenetic, goofy arena fighter, made in Unity. We plan to publish on mobile, first. I am tasked with creating an art pipeline which allows for customizable additions and color changes to the player's avatar. I'm trying to look ahead to when this character creator will be a part of the game and consider the performance implications of this kind of system. A character creator could potentially serve us in the generation of random NPCs at launch, and will feature heavily when we move to multiplayer.

My concern is with the number of draw calls on mobile. Currently, we have a bunch of identical characters, all creating instances of the main material on spawn to differentiate by random color. Since draw calls are directly linked to the number of materials onscreen, this process concerns me. Before complicating the issue with variations in mesh and texture on a per-object basis, having 1 material per character already limits us to a certain number of NPCs onscreen.

I delivered a material solution which allows changing one color to differentiate from other characters. Now the director is asking about the feasibility of breaking each character into multiple materials to allow for player customization. With 4 materials per character (1 shared), draw calls would increase geometrically per spawn. I've heard mobile platforms tend to be limited to about 20-120 draw calls between low and high end devices. That would make for 5-35 characters allowed onscreen at once, assuming we could get the environment down to  around 5 draw calls.

I would be especially interested in any material masking techniques people are aware of. Having a need for around 4 customizable aspects would seem to point towards using some sort of RGBA texturing and masking solution, but I have no idea how to make Unity do that.


texts: How can you implement Lua into your game?

texts: I am trying to implement Lua into my game, but am having trouble. Say I have a weapon class, which is just a hollow shell, lacking real functions. I was thinking of creating an onFire function, which will simply call a pointer to a Lua function that was created for that weapon. Is this the way most people do it? Are there any other ways?


texts:
We are making a multipler first person shooter.
The client sends it's position to the server at a fixed rate (currently at 10Hz). The server sends a single message contatining all player's positions to all players at the same rate (10Hz).

As expected, the movement is pretty choppy since the 60fps game is only recieving updates 10 times a second.
What is the best way to smooth this movement?
The most obvious way would be to interpolate between the last two packets, so that the interpolation finishes as we recieve a new packet. But this adds an instant 100ms delay for all players.

The other way would be to use the velocity and acceleration inferred from the last few packets to predict where the player is before the next packet arrives, however if the prediction is wrong, the player would tend to jump as soon as a new packet is recieved.

Does anyone know how AAA titles solve this problem?


texts:
In 2d, I have a ship that I want to have move to specific coordinates.
I've used Sidar's answer in  How do I calculate how an object will move from one point to another? to get something that works allright, but it overshoots and at the end the ship just jumps around the destination.
Basically the speed is 10, but the destination isn't a multiple of 10, so it can never be reached.
What would be a good way to prevent that ?

Currently the function looks like that (sorry, Haskell, but it should be easy enough to understand) :

  let n = normalize $ dest ^-^ cur in
  let (V2 dx dy) = n ^* speed in
  (curx + dx, cury + dy)

That's basically what's in Sidar's post, substract the destination coordinates with the current coordinates, normalize that, then multiply it by the speed and add that vector to the current coordinates to get the new ones.
The question is : is there a way to prevent that from overshooting the destination, ideally without adding an if for each direction for x and y (that would be a bit ugly, but I don't see how else) ?


texts: Convert Rainbow gradient Shader to 3 colors gradient

texts:
I am attempting to convert this rainbow shader into just using three colors.
I thought I would be able to set the three colors in the shader file, but I can't understand how to link them through the shader helper file.

shader: https://hastebin.com/uworiduluc.cs
Shader helper: https://hastebin.com/kifezufegi.cs

fixed4 frag(fragmentInput i) : SV_TARGET
{
    fixed2 lPos = i.localPosition / _Spread;
    half time = _Time.y * _Speed / _Spread;
    half timeWithOffset = time + _TimeOffset;
    fixed sine = sin(timeWithOffset);
    fixed cosine = cos(timeWithOffset);

    fixed hue = (-lPos.y) / 2.0;
    hue += time;

    while (hue < 0.0) hue += 1.0;
        while (hue > 1.0) hue -= 1.0;
            fixed4 hsl = fixed4(hue, _Saturation, _Luminosity, 1.0);

    return HSLtoRGB(hsl);
}

I added these properties at the top

_Color3 ("Top", Color) = (1,1,0,1)
_Color2 ("Middle", Color) = (1,1,0,1)
_Color1 ("Bottom", Color) = (1,1,0,1)

But I am not sure where I can add them into the code to have them be the colors that are used.


texts:
I've always had a hard time wrapping my head around the 'high levels' of game logic and where/how large components, such as collision detection/physics, rendering, and user input, interact with one another. What I'm asking is how you deal with these higher level interactions.

Here is what I am doing:

interface Stage() { //or a "scene" as many call it. Manages the logic for Actors
   init()
   update() //update this stage
   render() //render this stage
}

StageManager() implements Stage { //a stage that manages stages :)
   var stages = array<Stage>
   init() //create a MainStage & other stages that may be used in this specific game
   update() //logic for checking which stage should be active
   render() //tell the active stage to render
   getActiveStage()
}

MainStage() implements Stage {
   var mainCharacter
   var actors = array<GameObject>
   var ...
   init()   //create the player, game world, other initialization stuff
   update() //collision detection, check mainCharacter state, etc
   render() //render all the Actors on this stage
   handleMouseClick()
   handleKeyBoardEvent()
}

Main() { //created on game start
   var manager = new StageManager()
   updateGameState() {
      manager.update()
      loop
   }

   renderState() {
      manager.render()
      loop
   }

My main gripe with this is that the StageManager and all other Stages will become enormous and unwieldy as the game scales over time. Off the top of my head, some components can be delegated out such as a Stage uses a PhysicsManager, but there would still be all the keyboard events and what not.

I was thinking of making individual Actors listen to events and giving them an update() method, thus encapsulating what an Actor should do at any given point. However, I would run into complications when an Actor needed game-state information (game time, a "power-up" Actor needing the player's speed) and I would no longer have Stages as Actors are now managing themselves.


texts:
Is it possible on Android to render specifically / only, to the connected Monitor/TV on the hdmi port?

If so, is it possible to use OpenGL ES to render a different scene on the monitor and on the device's screen?

I would like the tablet to become more of an input device when it is connected with a monitor/tv and my game to be rendered just to this screen. If nothing is connected, then the device's screen should be used.

Ideally I would render a small interface (with buttons and text only) on the android tablet and the game itself on the monitor.
Can this be done? How?


texts:
This is my problem: I have a scheduled update, here I track the movements of my objects (sprites), I move them with CCMoveBy, and I need to constantly update the zOrder. For setting the zOrder I've made a setZOrder(), which it takes the actual position of the sprite.

And here is the problem, I get all the X and Y values after the object is in the target. I know I get the values after the object is in the new position because I've made a CCLog. I can read all the values from the sprite, only when it's in the new position, so everything is well sorted only when the objects are not moving.

How can I get the CCMoveBy values on every tick update? (or how can I get the CCMoveBy values in "real-time"?)

Here is an idea of my code.

this->schedule(schedule_selector(Game::update));

void Game::update(float dt)
{
   setZOrder();
   moveObjects();
}

void Game::setZOrder()
{
  //This function takes the X and Y position and the row and column where the sprite is.
  //Is working good. But I'm getting the "move" action values, after the object is in place.
}

void Game::moveObjects()
{
   for (i=0; i < numChildren; i++)
   {
     CCActionInterval* move = CCMoveBy::create(targetPoint, time);
     object[i]->runAction(move);
   }
}


texts: How can I implement a "20 Questions" algorithm?

texts:
Ever since childhood, I've wondered how the 20Q electronic game worked. You think of an object, thing, or animal (e.g. potato or donkey). The device then asks you a series of questions such as:

Is it larger than a loaf of bread?
Is it found outdoors?
Is it used for recreation?

For each question, you can answer yes, no, maybe, or unknown. I always imagined it work with immense, nested conditionals (if-statements). However, I think that's an unlikely explanation because of its complexity for the programmer.

How would I implement such a system?


texts: Why is the velocity of my rigid body in OnCollisionEnter always zero?

texts:
My object must explode when the player touches it or when it collides at a low speed.

The problem I'm having is that its speed becomes zero when the floor collides for example and then the OnCollisionEnter event is called, it is already late and never fulfills the condition.

Someone knows what I'm doing wrong or what I should do to fix this?

void OnCollisionEnter(Collision other)
{
    Debug.Log(Mathf.Abs(rb.velocity.magnitude));
    if (Mathf.Abs(rb.velocity.magnitude) >= detonationImpactVelocity)
        Explosion(200);

    if (other.gameObject.tag == "Player")
        Explosion (600);

}

I came up with this but I guess there must be a better way to do it.

void Update()
{
    if (Mathf.Abs(rb.velocity.magnitude) >= detonationImpactVelocity)
        explosionSpeedAchieved = true;
    else
        explosionSpeedAchieved = false;
    Debug.Log(Mathf.Abs(rb.velocity.magnitude));
}

void OnCollisionEnter(Collision other)
{
    Debug.Log(Mathf.Abs(rb.velocity.magnitude));
    if (explosionSpeedAchieved)
        Explosion(200);

    if (other.gameObject.tag == "Player")
        Explosion (600);

}


texts:
Im designing a game with both digital currency and player progression, but have hit a confusing snag, where I possibly can't be the first to come to a decent solution.

To keep it simple, it's a mobile game, where the player is identified by his Device ID in the beginning. He is encuraged to connect with facebook, and if he does so, will be identified by his Facebook User ID (FBID) instead. For security reasons (and because its core to the game) you can only play online, and progression and resources are maintained by the server.

So far, the flow is simple:

If the server has no FBID on the user, an account is created based on his DeviceID, and he plays on that.
If the user connects to facebook, the account is updated with the new FBID, and all resources are carried over.
If the player deletes the app, and redownloads it, we still identify him based on device id, and he gets his old account back.

But here are the area that I'm concerned:

If the same player has a second device, he would like to play from instead/also.

It's a fair scenario that if the player requires an tablet next to his phone, and he wants to play with the same account.

So my play so far, is to wipe the "temporary account" from the server, find the account with the matching FBID, and add this new device to an array of devices on the original account.

I have session based control, so they can't be playing on the same time. The old device will simply be logged out if the same user appears on the new one.

But I have a feeling this is not the best way of doing things. What if the "temporary" game is played by someone else, and that person will technicly get his account wiped and device "taken over" by the logged in user ? Im especially concerned about family-type scenarios, where devices are shared.

Does anyone have any good suggestions on structure on this ? Maybe I'm completely in the woods with my method here, and doing it all wrong.

My priorities are :

Duplication of ingame resources must not occur
A player should never be "punished" by starting over, if he signs in using facebook.
A player should be able to maintain and restore his progress in the game, even if he logs out.


texts: Projectile Rotation During Flight (Tank Game)

texts:
I have a tank firing projectiles into the air.

I want the projectiles to be rotated relative to their position along their flight path.

See the diagram I drew in the image below.

At any given point I know the x and y of the projectile, z represents initial velocity, theta is also known.


texts: Unity in c# errors with "the type does not contain a constructor that takes 0 arguments"

texts:
This is the problematic line

datosAguardar datos = new datosAguardar ();

Here is my code

public class estadoJuego : MonoBehaviour {

public int puntuacionMaxima = 0;
public static estadoJuego estadojuego;
private string rutaArchivo;

void Awake ()
{
    rutaArchivo = Application.persistentDataPath + "/datos.dat";
    if (estadojuego == null)
    {
        estadojuego = this;
        DontDestroyOnLoad (gameObject);

    }  else if (estadojuego != this)
    {
        Destroy (gameObject);
    }
}

// Use this for initialization
void Start ()
{
    cargar ();
}

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

}

public void guardar ()
{
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream file = File.Create (rutaArchivo);

    datosAguardar datos = new datosAguardar ();

    datos.puntuacionMaxima = puntuacionMaxima;

    bf.Serialize (file, datos);

    file.Close ();
}

void cargar ()
{
    if (File.Exists (rutaArchivo))
    {
        BinaryFormatter bf = new BinaryFormatter ();
        FileStream file = File.Open (rutaArchivo,FileMode.Open);

        datosAguardar datos = (datosAguardar)bf.Deserialize (file);

        puntuacionMaxima = datos.puntuacionMaxima;

        file.Close ();
    }  else
    {
        puntuacionMaxima = 0;
    }
}

[Serializable]
//definiendo la clase
class datosAguardar  //: ISerializable

{
    //propiedades de la clase
    public int puntuacionMaxima ;
    //metodo de la clase
    //constructor de la clase
    public datosAguardar (int puntuacionMaxima) // : base (puntuacionMaxima)
    {

        this.puntuacionMaxima = puntuacionMaxima  ;
    }

}

This is the constructor

[Serializable]
//definiendo la clase
class datosAguardar  //: ISerializable

{
    //propiedades de la clase
    public int puntuacionMaxima ;
    //metodo de la clase
    //constructor de la clase
    public datosAguardar (int puntuacionMaxima) // : base (puntuacionMaxima)
    {

        this.puntuacionMaxima = puntuacionMaxima  ;
    }

}


texts: Is there any specific reasons to include clearly inferior options in a game?

texts:
Games contain inferior options
A lot of games that I have played contain some optimal options and some clearly inferior ones. Sometimes, like in Heroes of Might&Magic IV, it could happen due to the limited time the developers had to balance it (e.g. Academy benefits so much more from choosing Gold Golems and then Genies rather than Magi and Naga that there is no reason to go the second way).
Sometimes it happens for no apparent reason
However, it often happens that the developers clearly had enough time to polish the game, didn't go bankrupt after its release etc., but it is still full of "trap" options that sound cool, but are actually inferior to something always available in the same situation, or almost always available in similar situations.
There are just so many examples of such, almost every game has something like that. For example, Age of Wonders I began a successful series thga, but a lot of abilities to be chosen for the heroes are clearly underperforming, and a lot of units have clearly better alternatives on the same levels in the same factions.
It is important that while some very overpowered stuff often gets nerfed (like it also happened in AoW I), the obviously underpowered choices often stay as they are (as it also happened there).
So, I ask: Why do game developers create clearly inferior options in their games and don't rebalance them? Is it intentional? If it can be avoided -- how?


texts:
Currently I am using arrays to handle all of my game objects in the game I am making, and I know how terrible this is for performance.  My question is what is the best way to handle game objects and not hurt performance?

Here is how I am creating an array and then looping through it to update the objects in the array:

public static ArrayList<VboCube> game_objects =  new ArrayList<VboCube>();
/* add objects to the game */

while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
        for (int i = 0; i < game_objects.size(); i++){
            // draw the object
            game_objects.get(i).Draw();
            game_objects.get(i).Update();
            //world.updatePhysics();
        }
}

I am not looking for someone to write me code for asset or object management, just point me into a better direction to get better performance. I appreciate the help you guys have provided me in the past, and I dont think I would be as far along with my project without the support on stack exchange!


texts: Math behind XNA's spriteBatch.draw() color parameter?

texts:
I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks.

Say you set the parameter to 'Red' -- white pixels in the original texture would  become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish.

If you set the parameter to 'Black' the texture would become completely black.

Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it.

Thanks!


texts: poor performance with kinect sdk and xna (color stream)

texts:
I'm trying to make an augmented reality game for advertisement, using the kinect sdk 1.6 and xna 4.0.  I need to use the color image format rgb 1280X960, in spite of the fact that it runs at 12fps, because the quality of the image is important for this project. The problem is that when I call the function to build a color image frame, the fps of the game drops a lot.  When I use only skeleton frame information to build a game scene, it runs at 50/60 fps, but when I call the function for the color frame the frames drop to 10/14 fps.  The purpose of this function is the transformation of the stream to bgra format.  If I comment out this loop, I get 30/40 fps.  Is there any other way to make this more efficient?

public Texture2D Video()
{
   try
   {
      if (video == null)
        video = new Texture2D(gd, Sensor.ColorStream.FrameWidth, Sensor.ColorStream.FrameHeight);

      ColorImageFrame framecolor = Sensor.ColorStream.OpenNextFrame(100);

      if (framecolor != null)
      {
        byte[] bgraPixelData = new byte[framecolor.PixelDataLength];
        framecolor.CopyPixelDataTo(bgraPixelData);

        //Convert RGBA to BGRA
        byte[] colorbuffer = new byte[framecolor.PixelDataLength];

        for (int i = 0; i < bgraPixelData.Length; i += 4)
        {
          colorbuffer[i] = bgraPixelData[i + 2];
          colorbuffer[i + 1] = bgraPixelData[i + 1];
          colorbuffer[i + 2] = bgraPixelData[i];
          colorbuffer[i + 3] = (byte)255; //The video comes with 0 alpha so it is transparent
        }

        video.SetData(colorbuffer);
      }

    }
    catch
    {
      video = null;
    }

    return video;
  }

-----How do i ressolve it?

I finally decide to use a shader to make the gpu deal with the process of tranform between formats, as it was suggested by @Seth Battin. this is the shader:

sampler sprite : register(s0);

/*
 * Convert from BGRX to RGBA
 */
float4 BGR2RGB(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 tex = tex2D(sprite, texCoord);
    return float4(tex.b, tex.g, tex.r, 1.0);
}

technique KinectVideo
{
    pass KinectVideo
    {
        PixelShader = compile ps_2_0 BGR2RGB();
    }
}

and the code i used before, as it no longer need to make the transform, now looks like this:

public RenderTarget2D Video()
        {
            try
            {
                if (Sensor != null)
                {
                    if (Sensor.ColorStream != null)
                    {
                        using (var frame = Sensor.ColorStream.OpenNextFrame(0))
                        {
                            if (frame != null)
                            {
                                if (buffer == null || buffer.Length != frame.PixelDataLength)
                                {
                                    buffer = new byte[frame.PixelDataLength];
                                }

                                frame.CopyPixelDataTo(buffer);
                                //GraphicsDevice.Textures[0] = null;

                                videoframe.SetData<byte>(buffer);

                            }
                        }
                    }
                }
            }
            catch
            {
            }
            return videoframe;
        }

I know that the try/catch its expensive, but now i have a good rate of fps, and its woorking fine.
After that, i just apply the shader in the draw call, like this:

                sb.Begin(SpriteSortMode.Texture, null, null, null, null, kinectcolorvisualizer);
                sb.Draw(video, pantalla, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
                sb.End();

where "sb" is spritebatch, "kinectcolorvisualizer" is the shader and "video" is the RenderTarget2D returned by the video function

Thanks to @Seth Battin and to @Mustafa Karakuş for their help.


texts: Light direction not being calculated correctly

texts:
I'm trying to implement deferred lighting in my game, and have run into an issue with normals.

The image above shows the lighting being applied to a tile map. The yellow shade represents the direction of the light at that pixel. The character has a green normal so when he is below the light as he is in the screenshot, he doesn't get lit. I was working through the problem of the character always being lit, and it seems to be because the light direction isn't calcualted correctly. I expect the light direction color to be a rainbow of colors, however the yellow means that the light is always point down X and Y axis instead of radiating out in a circle. I'm certain that worldPos is coming out correct because the diffuse/normal colors are being displayed correctly.

Fragment shader for the light:

#version 330

uniform sampler2D diffuseTexture;
uniform sampler2D normalsTexture;
in vec2 TexCoords;

out vec4 outColor;

void main(void) {
    vec2 resolution = vec2(200, 200);
    float distance = length(vec3((TexCoords*resolution) - (resolution / 2),
                                0.0));
    float constantAttenuation = 1.0;
    float linearAttenuation = 0.1;
    float quadradicAttenuation = 0.01;

    float attenuation = 1.0 / (constantAttenuation +
    (linearAttenuation*distance) + (quadradicAttenuation*distance*distance));

    vec3 worldPos = gl_FragCoord.xyz / vec3(1024, 768, 1.0);
    vec3 lightDir = normalize(vec3(50,50,10) - worldPos);

    float diffuseFact = dot(normalize(texture2D(normalsTexture, worldPos.xy).rgb), lightDir);

    vec4 diffuse = vec4(0.0);

    if(diffuseFact > 0.0) {
        diffuse = vec4(texture2D(normalsTexture, worldPos.xy).rgb, 1.0);
        diffuse = diffuse * diffuseFact * 10;
    }

    outColor = vec4(lightDir, 0.5) + (diffuse*attenuation);
}


texts: Learning C++, algorithms and vectorial algebra

texts:
I need your recommendations for a good study source about videogame orientated C++, algorithms and vectorial algebra.

I will be applying to a videogame programmer course in January so I need to start getting ready asap.

Cheers!


texts:
I'm creating hexagonal prisms from code and am having a difficult time understanding how UV mapping works, as the texture I apply to the hexagonal face comes out skewed:

Forgetting the sides for now, here is how I'm creating the hexagonal face:

    meshData.vertices.Add(new Vector3(x, y + 0.5f, z + 0.5f)); // N
    meshData.vertices.Add(new Vector3(x + 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z + 0.5f / 2)); // NE
    meshData.vertices.Add(new Vector3(x + 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z - 0.5f / 2)); // SE
    meshData.vertices.Add(new Vector3(x, y + 0.5f, z - 0.5f)); // S
    meshData.vertices.Add(new Vector3(x - 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z - 0.5f / 2)); // SW
    meshData.vertices.Add(new Vector3(x - 0.5f * (Mathf.Sqrt(3) / 2), y + 0.5f, z + 0.5f / 2)); // NW

This creates a regular hexagon. My texture is also a regular hexagon. So why does it get textured at an angle?

Here is my UV code:

    meshData.uv.Add(new Vector2(0.5f, 1));
    meshData.uv.Add(new Vector2(1, 0.75f));
    meshData.uv.Add(new Vector2(1, 0.25f));
    meshData.uv.Add(new Vector2(0.5f, 0));
    meshData.uv.Add(new Vector2(0, 0.25f));
    meshData.uv.Add(new Vector2(0, 0.75f));


texts: Which parts to draw in an infinite world?

texts:
I have an infinite world (from Perlin Noise).

The world is generated in sectors that are that are big cubes (each with a random colour, in the image above; my sectors are 10x10x10).

I'm currently putting the sectors in a hash-table tagged by their top-left-front corner coordinate.  I can loop through all the sectors I've already generated and see if they intersect the frustum.

But how can I compute instead the sectors that I haven't generated but are visible and need generating on-demand?

Even if I have an octree or some other spatial index, I need to compute the sectors that are visible inside the frustum rather than those I've already generated.


texts: How could I implement programming as a mechanic?

texts:
I am wondering how I could manage to execute programs made by players in my game via some sort of in-game computer. I have been trying to figure it out but I have no idea how it is even possible.

Examples of other games that do this are:

ComputerCraft
Space Engineers
Screeps
Glitchspace

I just need a basic explanation of how I could do it so I can start making my own games with in-game coding as a mechanic.


texts: Unity3d - How to freeze a Animation in the Editor

texts:
Is it possible to freeze my Animation in the Editor at a specific frame?

I made a simple camera animation, I try to select a specific frame inside of that animation and pause it, so I can work in the editor with everything positioned at the current positions at that specific frame.

This does not work at the moment. If I select my desired frame and then select another object, then my animation is set to start again.

This makes it very hard to work in the editor and prepare the animation.

EDIT:

Ok I try to explain it more simple. Let's assume I am animating the main camera and I have three animation points, A, B, and C.  (I know I have more, but lets just assume it for this example to simplify it)

At A the camera is obviously at the start position:

At at B it is somewhere in between A and C:

At C the camera is at the end position:

What I need is to pause the animation at B, so my animation object stays at this position the whole time, even though when it has no focus and another object is selected. This would make it much easier for me to place objects exactly where I need them.

What actually happens is that my animated object (maincamera) is set to it's "start position", but I need it to stay in place, so I can place other objects perfectly.

I hope that was clear enough.

(side note: as you can see this is bugged, the rotation is weird now...)


texts: 2d water animation is jagged and not smooth

texts:
As a solution for this question I implemented the shader with a test program:

import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShaderProgram

class ShaderTestApp : ApplicationAdapter() {
  lateinit var batch: SpriteBatch
  lateinit var noiseTexture: Texture
  lateinit var sprite: Sprite
  lateinit var shaderProgram: ShaderProgram

  private val vertexShaderString = """
    attribute vec4 a_position;
    attribute vec4 a_color; //required by libgdx
    attribute vec2 a_texCoord0;

    uniform mat4 u_projTrans;

    varying vec4 v_color;
    varying vec2 v_texCoords;

    void main() {
      v_color = a_color;
      v_texCoords = a_texCoord0;
      gl_Position = u_projTrans * a_position;
    }
  """.trimIndent()

  private val fragmentShaderString = """
     #ifdef GL_ES
      precision mediump float;
  #endif

  varying vec4 v_color;
  varying vec2 v_texCoords;

  uniform sampler2D u_noise;
  uniform sampler2D u_texture;
  uniform mat4 u_projTrans;

  uniform float u_noise_scale;
  uniform vec2 u_noise_scroll_velocity;
  uniform float u_distortion;
  uniform float u_time;

  void main() {
          vec2 waveUV = v_texCoords * u_noise_scale;
          vec2 travel = u_noise_scroll_velocity * u_time;
          vec2 uv = v_texCoords;
          uv = uv + (u_distortion * (texture2D(u_noise, waveUV + travel).rgb - 0.5));
          waveUV += 0.2;
          uv = uv + (u_distortion * (texture2D(u_noise, waveUV - travel).rgb - 0.5));
          vec3 color = texture2D(u_texture, uv).rgb;
          gl_FragColor = vec4(color, 1.0);
  }
  """.trimIndent()

  override fun create() {
    batch = SpriteBatch()
    val img = Texture("background/water-surface-reflection-withBg.png")
    img.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat)
    noiseTexture = Texture("background/gradient.png")
    noiseTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat)
    sprite = Sprite(img)
    sprite.setSize(Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat())

    shaderProgram = ShaderProgram(vertexShaderString, fragmentShaderString)
    if (!shaderProgram.isCompiled) {
      println(shaderProgram.log)
    }
  }

  var time = 0f
  override fun render() {
    time += Gdx.graphics.deltaTime
    Gdx.gl.glClearColor(1f, 0f, 0f, 1f)
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

    batch.begin()
    noiseTexture.bind()
    shaderProgram.setUniformf("u_noise_scale", 0.1f)
    shaderProgram.setUniform2fv("u_noise_scroll_velocity", floatArrayOf(.006f, .007f), 0, 2)
    shaderProgram.setUniformf("u_distortion", 0.04f)
    shaderProgram.setUniformf("u_time", time)
    batch.shader = shaderProgram
    batch.draw(sprite, sprite.x, sprite.y, sprite.width, sprite.height)
    batch.end()
  }
}

object ShaderTestLauncher {
  @JvmStatic
  fun main(arg: Array<String>) {
    val config = LwjglApplicationConfiguration()
    config.samples = 2
    config.width = 640
    config.height = 640
    LwjglApplication(ShaderTestApp(), config)
  }
}

Which looks like this:


texts:
So I am somewhat new to working with DirectX rendering, and I have done some 2d and 3d work.  I am planning on working on a new application where I will be rendering a bunch of 3d scenery, and then overlaying some 2d 'sprites'

My plan is to draw the 3d stuff, then change to an orthographic projection for the 2d stuff and so on.  I was wondering if this was a normal thing to do, or if I am somehow going to be shooting myself in the foot later because of performance problems, etc.

Sorry if the question is vague, I don't quite know enough to be more technical / elaborate.


texts:
For a college project I need to draw an empty cube and then show the cube being filled.

So far I have heard that JME and voxels is the way to go but I have no idea where to start. Can anyone point me towards a tutorial or any reading?

My project is in Java but any pseudo-code is welcome.


texts: How to get the normal that points *out* of a polygon

texts:
In 2D, each vector (x, y) has two normals: (-y, x) and (y, -x), pointing in opposite directions.

Say I have a polygon and for each of it's edges I need to get the normal pointing outwards. In the picture below, the red normals:

For each edge of the shape, how can I decide if I need (-y, x) or (y, -x)?


texts: how to remove game objects after on overlap in LIBGDX game

texts:
I have gold stars in my game that give score to game hero if the hero overlap with the star. What I want is to remove star once it overlap with hero object.
I give score by checking overlap with this code

public void scorecount(Hero myhero){

            if (!star.isScored() && Intersector.overlaps(myhero.getBoundingBalloon(), star.getStarCircle()))
    {

                addScore(1); // give one plus always
  star.setScored(true);

AssetLoader.coin.play();

}

Now once I give score and setScore true , i want to remove star.
How can I do that?
I tried for setvisible method but I dont know how to use it. Because just Calling star.setVisible() ask to create this method in star class. then in star class I dont know what should be given inside this method body.


texts: What algorithms are used for force dispersal between rigid objects attached by joints?

texts:
I have in mind a 2d, side-scrolling game which requires the construction of vehicles and/or structures built of conjoined rigid structures, like beams or platforms.  These structures will be impacted from various angles.

What algorithms and data structures are used typically in, say, bridge-building games, to determine the force dispersal between such attached, rigid objects, and at what point the joints bend or break?


texts: How can I implement platformer pathfinding?

texts: I've gone through A* pathfinding but could find anything on this. What I'm looking for is pathfinding for something kind of like a super smash bros level with different platforms. Can anyone point me in the right direction?