texts:
I searched for hours on google and Unity Documentation & forums for information or tutorials on how to do this, but I can't find anything.

I'm trying to write an editor script who'll allow me to edit a zone in the scene view.

I found a way to do it and it works, BUT I really find this solution not aesthetic at all, here's how it looked :

And that's my code to achieve that :

[CustomEditor(typeof(CameraZone))]
public class CameraZoneEditor : Editor
{

    void OnSceneGUI()
    {
        var zone = (CameraZone)target;

        Handles.DrawSolidRectangleWithOutline(new Rect(zone.transform.position, zone.size), zone.editorColor, Color.black);
        Handles.color = Color.white;

        var center = zone.transform.position + ((Vector3)zone.size / 2);

        var handlesPos = new [] {
            new Vector3(center.x + zone.size.x / 2, center.y, center.z),
            new Vector3(center.x - zone.size.x / 2, center.y, center.z),
            new Vector3(center.x, center.y + zone.size.y / 2, center.z),
            new Vector3(center.x, center.y - zone.size.y / 2, center.z)
        };

        var posRight = Handles.Slider(handlesPos[0], Vector2.right);
        var posLeft = Handles.Slider(handlesPos[1], Vector2.left);
        var posUp = Handles.Slider(handlesPos[2], Vector2.up);
        var posDown = Handles.Slider(handlesPos[3], Vector2.down);

        var rect = new Rect(posLeft.x, posDown.y, posRight.x, posUp.y);
        zone.size = rect.size;
    }

}

This is working just how I want it to (except that the bottom and left arrows are not resizing the zone but that's not a problem for now).

Now to make it more beautiful, I wanted to replace the arrows with simple cubes, I've seen that I can do that with Handles.CubeHandleCap delegates so I made some to test it. It looks exactly how I want them to but I'm unable to resize the zone now, when I try to drag it it just unselect the GameObject.

Here's how it looks now :

And here's the code I wrote to do that :

[CustomEditor(typeof(CameraZone))]
public class CameraZoneEditor : Editor
{

    void OnSceneGUI()
    {
        var zone = (CameraZone)target;

        Handles.DrawSolidRectangleWithOutline(new Rect(zone.transform.position, zone.size), zone.editorColor, Color.black);
        Handles.color = Color.white;

        var center = zone.transform.position + ((Vector3)zone.size / 2);

        var handlesPos = new [] {
            new Vector3(center.x + zone.size.x / 2, center.y, center.z),
            new Vector3(center.x - zone.size.x / 2, center.y, center.z),
            new Vector3(center.x, center.y + zone.size.y / 2, center.z),
            new Vector3(center.x, center.y - zone.size.y / 2, center.z)
        };

        Handles.CapFunction rightFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[0], Quaternion.identity, 0.2f, EventType.Repaint);
        Handles.CapFunction leftFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[1], Quaternion.identity, 0.2f, EventType.Repaint);
        Handles.CapFunction upFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[2], Quaternion.identity, 0.2f, EventType.Repaint);
        Handles.CapFunction downFunc = (id, position, rotation, size, type) => Handles.CubeHandleCap(0, handlesPos[3], Quaternion.identity, 0.2f, EventType.Repaint);

        var posRight = Handles.Slider(handlesPos[0], Vector2.right, 0.2f, rightFunc, 0.1f);
        var posLeft = Handles.Slider(handlesPos[1], Vector2.left, 0.2f, leftFunc, 0.1f);
        var posUp = Handles.Slider(handlesPos[2], Vector2.up, 0.2f, upFunc, 0.1f);
        var posDown = Handles.Slider(handlesPos[3], Vector2.down, 0.2f, downFunc, 0.1f);

        var rect = new Rect(posLeft.x, posDown.y, posRight.x, posUp.y);
        zone.size = rect.size;
    }

}


texts: How can i change the cube scale only on Y and only to up?

texts:
This is the script I am working with:

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

public class Raise : MonoBehaviour
{
public GameObject Ladder;

float mfX;
float mfY;
float mfZ;
// Use this for initialization
void Start()
{
    mfX = Ladder.transform.position.x - Ladder.transform.localScale.x / 2.0f;
    mfY = Ladder.transform.position.y - Ladder.transform.localScale.y / 2.0f;
    mfZ = Ladder.transform.position.z - Ladder.transform.localScale.z / 2.0f;
}

// Update is called once per frame
void Update()
{
        Vector3 v3Scale = Ladder.transform.localScale;
        Ladder.transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y + 0.1f, v3Scale.z + 0.1f);
        Ladder.transform.position = new Vector3(/*mfX + Ladder.transform.localScale.x / 2.0f*/0, mfY + Ladder.transform.localScale.y / 2.0f, mfZ + Ladder.transform.localScale.z / 2.0f);
}
}

The way it is now it's making the whole cube bigger and bigger.

But I want to make the cube grow only UP on Y. To keep the cube capacity/ extent
But to make the scale change only up.

If I'm doing:

Vector3 v3Scale = Ladder.transform.localScale;
Ladder.transform.localScale = new Vector3(0, v3Scale.y + 0.1f, 0);
Ladder.transform.position = new Vector3(0, mfY + Ladder.transform.localScale.y / 2.0f, 0);

I will see it go up in scene if I select the cube in the hierarchy but if not I will not see the cube at all.

Can't figure out how to make is grow up only up side.


texts: How to check version of Unity package in project through script

texts:
I'm writing an asset that will be used by many people, but it depends on TextMeshPro (TMP). I ran into a bug in TMP that can only be fixed by upgrading to a preview version. I want to warn users that install my asset that they need to upgrade their TMP version if they are using a prior version. Surprisingly, I can't find this anywhere online or in the docs.

just something like

if (TextMeshPro.version < MyAsset.RequiredTMPVersion) {
    Debug.LogError("Need to upgrade TMP");
}


texts: Pixel perfect collision detection between sprite and animated sprite

texts: I am trying to make a collision between a sprite and an animated sprite. The animated sprite is the main character of the game. The problem I am facing is that when another sprite collides with the main character, it collides with the transparent bounding area around the character. How should I perform collision detection between the actual pixels of the character and any other obstacle sprite?


texts:
I'm developing prototype of Tower Defense/RTS game and I've implemented simple Flow Field grid. Here is the example (link).

How to use example: First click on S50, this will spawn additional units, then wait till all of them clump together, click on SET_BASE button and click on a free space, this will move the base (red circle) and they'll move to the new location. The problem is that if you click to a relatevely diagonal position, they'll all go straight to the target, while if you give them new order at the same y coordinate, they'll start clumping.

If you click several times to move units around, you'll notice that they're moving pretty well when you order them to move diagonally and clump in a line when going horizontally or vertically.

I ran out of ideas what to do next to fix this, what are yours?

A bit more info about my flow field: I do one pass of "Dijkstra distance" and then do second pass of detecting lowest distance neighbor and assign "vector" to that neighbor.

Then, about units movement - every unit every update reads "desired movement vector" from it's current cell, predits its movement, then checks if it will hit the wall, updates movement vector, then checks if it will hit other units and finally updates movement vector.

EDIT: Here's the source code of movement logic.(link)

And source of flow field generation (link)

I'm sorry for shitty code and stupid comments, it's all "prototyp-ish" as possible.

What I want is to achieve less "diagonal-horizontal" difference, because at the current state it's really seem underwhelming and it's unaccetable that you can move all units faster by zig-zagging them to their destination.


texts: Integer vs String for "type" data in data-driven games

texts:
I've been developing a few mobile games, in which those games fetch their data from a server-database.

I'm used to storing "type" values as an integer identifier, and an enum in the client to identify the data coming from the server.

I'm under the impression that games like MMOs or PC games that get patches model their data to identify "types" as integers.

As an example: On the database table:

Monsters Table: MonsterId(int), Name(string), MonsterType(int)

On the client-sided code:

typedef enum {
    MonsterTypeGround = 1,
    MonsterTypeAquatic = 2,
    MonsterTypeAmphibious = 3,
    MonsterTypeAerial = 4
}MonsterType;

Is there an objectively correct answer on what to use (int vs string) for these types of data?

Do I have the correct impression that MMO's usually use integers for this, or it highly depends on the developers as well?


texts: What is the best designed open source game engine to take example?

texts:
Possible Duplicate:
  Where can I find good (well organized) examples of game code?

I have coded several C++ games and now I'm building my own game engine and editor.

I have some doubts about the design and I wish to find great examples to follow.

What is the best designed in your opinion?

Must be object oriented. Programming language does not matter, but I prefer in this order: C++, C#, Java or another similar.

EDITED: To clarify more, I'm not interested on game-specific code. I want general purpose game engines.

EDITED: This article explains what is a game engine: game engine at wikipedia and here is a list of known game engines: list of game engines at wikipedia


texts:
I have a 3D field with many MovieClips in it, and seems like the one last added is the one  that overlaps others and not the one with highest z value.
Is there any property/function that sets z-index? (sorting children by z value seems too much like a hack).
A 3D engine that can place MovieClips will be helpful(but not one that requires custom drawing).
I'm using Flash CS5 with ActionScript 3


texts:
I'm trying to get postprocessing work again after updated to URP. But it does not work !!

Could anyone help me with any solution or clue ?


texts:
In my game I have a rocket which is traveling horizontally across the screen.

What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect.

How do I do this?


texts: Avoiding impossible states in an adventure game

texts:
I'm looking at creating a fairly complex choose-your-own adventure style of game, but I'm looking for a technique or method to help with the game design.

It will be a multi-branching story, and at times the branches will fold back in on themselves, and your major actions will be remembered and items will be collected.  For example, if the player goes to the swamp and the forest before going to the castle he has picked up a dinosaur bone, killed a unicorn and grown an extra arm.  If a player gets to the castle via the caves and the crypt he has picked up a bicycle and a strange smell.
Now when developing puzzles for the castle I don't want to create a situation where two impossibilities are requires, for example - an extra arm and the smell are needed to kill an ogre.

Other than documenting the events and items very very carefully is there a process, a technique I can use in a spreadsheet or a piece of software that can help me?


texts: TBN Matrix : Eye vs. World Space Conflict

texts:
I am tired of misleading and insufficient articles making me more confused each time I read, I need a clarification that will solve my TBN matrix problem forever.

Each article I read informs me differently about from which space TBN matrix converts to tangent space. One article says that it converts from eye space, other one says that it converts from world space  to tangent space.

As far as I know, world space is ModelMatrix * vertex, eye space is ViewMatrix * ModelMatrix * vertex. Another article says that transpose of TBN Matrix actually does it.

Can you please explain me how to use TBN matrix, does it (or transposed tbn) convert from eye or world to tangent ? Should I convert my lighting vectors from eye space to world and then apply TBN on them ?


texts: Why do my objects with colliders go through each other, and how do I fix it?

texts:
I am new to Unity and I am just experimenting with a player controller script (which I got off youtube) and another object which doesn't move. Both my player and the stand-alone object have colliders and rigidbodies but when I move the player it goes straight through the other object.

My player controller script is:

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

public class PlayController : MonoBehaviour
{
    public float speed;

    private Rigidbody2D rb;
    private Vector2 moveVelocity;

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

    void Update()
    {
        Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        moveVelocity = moveInput.normalized * speed;
    }

    private void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
    }
}

Nothing has been changed on the colliders (nothing ticked), and the rigidbody2D has been changed to kinematic.


texts: Why it takes some time to update the sprite draw order in libgdx SortedIteratingSystem?

texts:
I have a rendering system that extends SortedIteratingSystem and created a comparator to sort the sprite draw order. But the problem is when I update the z index, it takes some time before it changes the order.

public class RenderingSystem extends SortedIteratingSystem {

    public RenderingSystem() {
        super(Family.all(...components).get(), new ZComparator());
    }

    private static class ZComparator implements Comparator<Entity> {
        @Override
        public int compare(Entity e1, Entity e2) {
            return (int)Math.signum(Mappers.index.get(e1).z - Mappers.index.get(e2).z);
        }
    }

}

IndexComponent implements Component {
    public int z = 0;
}


texts: Is it possible to compile both VS and PS in a single file in VS2012?

texts:
VS2012 has a built-in option for compiling *.hlsl files at compile time (e.g. to check for errors). But from what I've seen it requires me to provide the entry point (function) name for each file. What if I have both Vertex Shader and Pixel Shader in 1 file? Is it possible to make VS2012 still compile that file (both shaders) to check for errors?

I know it's possible with Custom Build Tool option and using fxc in the Command Line (I just tell it to compile the file without specifying the entry point). But since by default VS2012 is using fxc as well I thought it should be possible to compile 2 shaders in a single file when choosing HLSL Compiler option, too.


texts:
To be clear because the title is slightly ambiguous:
I understand that to check for collision detection it's (box.x > otherBox.x && box.x < otherBox.x + otherBox.w) etc.

However I'm curious about things to do after this, how can I sort of keep the player from entering the other object that they're supposedly colliding with without fully stopping them and therefore suspending them from movement?


texts: Speedup Dev process for bug fixing and debugging in Unity?

texts:
We're using Unity 2017 for a big Indie game. at the moment We have some issues with our development speed:

In order to fix issues and bugs, We used the visual studio and attach the process to Unity and go through the code step by step. every time we change something (even just a line of code) we back to unity and wait for all scripts to recompile which takes up to 1 minutes sometimes. after that, we run the game and go to the place that bug happened which takes us about two minutes.

  I was wondering if there was a Best practice for fixing issues and
  debugging in Unity which brings us speedup on script compiles and also
  helps us to get to bug location faster.


texts: Unity sizeDelta of an Image update opposite to what it should

texts:
I have an IEnumerator coroutine in which I call the UIManager script to update the Image size to fit the text size but it doesn't happen. when I use yield return new WaitForEndOfFrame() it sometimes solve the problem. but I don't want to use it.

edit: I tested the code like I was suggested in an empty unity project and it still happens, the width should change according to the text size but it happens opposite (when the text is small the width of the image is large and when the text is large the width of the image is small) (it only happens correctly at the first time - the width of the image fits the text width)

public class Example : MonoBehaviour
{
    public Image image;
    public Text text;
    private int k = 0;

    public void ButtonClick()
    {
        text.text = (k % 2 == 0) ? "10" : "10 / 10";
        image.rectTransform.sizeDelta = new Vector2(text.rectTransform.rect.width, 30);
        k++;
    }
}

edit: Solved! thanks for the help, Canvas.ForceUpdateCanvases() did the trick


texts: How do I render text in a view in SFML 2.5.1 without artifacts?

texts:
I'm using the following code to render text in a letterboxed view.

#include <iostream>
#include <random>
#include <math.h>
#include <cstring>
#include <ostream>

#include <SFML/Graphics.hpp>

const float FIXED_UPDATE_TIME = 16.67f;//60fps

const unsigned int DEFAULT_CAMERA_WIDTH = 1280;
const unsigned int DEFAULT_CAMERA_HEIGHT = 720;

sf::View get_letterbox_view(sf::View view, int window_width, int window_height) {

    // Compares the aspect ratio of the window to the aspect ratio of the view,
    // and sets the view's viewport accordingly in order to archieve a letterbox effect.
    // A new view (with a new viewport set) is returned.

    float window_ratio = window_width / (float) window_height;
    float view_ratio = view.getSize().x / (float) view.getSize().y;
    float sizeX = 1;
    float sizeY = 1;
    float posX = 0;
    float posY = 0;

    bool horizontal_spacing = true;
    if (window_ratio < view_ratio)
        horizontal_spacing = false;

    // If horizontal_spacing is true, the black bars will appear on the left and right side.
    // Otherwise, the black bars will appear on the top and bottom.

    if (horizontal_spacing) {
        sizeX = view_ratio / window_ratio;
        posX = (1 - sizeX) / 2.f;
    }

    else {
        sizeY = window_ratio / view_ratio;
        posY = (1 - sizeY) / 2.f;
    }

    view.setViewport( sf::FloatRect(posX, posY, sizeX, sizeY) );

    return view;
}

int main() {
    sf::RenderWindow window(sf::VideoMode(DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT), "Adventure of Jaggy Font Edges");
    window.setMouseCursorVisible(false);

    // Set up resource
    sf::Font fnt;
    fnt.loadFromFile("res/fnt/Ruda-Regular.ttf");

    // Set up text
    sf::Text text;
    text.setFont(fnt);
    text.setString("TEXT RENDERING");
    text.setCharacterSize(128);
    text.setFillColor(sf::Color::White);
    text.setOutlineColor(sf::Color::Black);
    text.setOutlineThickness(3.f);

    // Center text (in world space, I believe?)
    sf::FloatRect text_rect = text.getLocalBounds();
    text.setOrigin(
        floorf(text_rect.left + text_rect.width/2),
        floorf(text_rect.top + text_rect.height/2)
    );
    text.setPosition(0, 0);

    // Set up view, and center it on the text
    sf::View camera_view(sf::FloatRect(0.f, 0.f, DEFAULT_CAMERA_WIDTH, DEFAULT_CAMERA_HEIGHT));
    camera_view.setCenter(0, 0);

    sf::Clock clock;

    while (window.isOpen()) {
        // only update 60fps
        sf::Time elapsed_time = clock.getElapsedTime();
        if (elapsed_time.asMilliseconds() < FIXED_UPDATE_TIME) {
            continue;
        }

        // handle events
        sf::Event event;
        while (window.pollEvent(event)) {
            // window closed event
            if (event.type == sf::Event::Closed) {
                window.close();
            } // window resized event/*
            else if (event.type == sf::Event::Resized) {
                camera_view = get_letterbox_view(camera_view, event.size.width, event.size.height);
            }
        }
        window.clear(sf::Color(255, 255, 255, 255));

        window.setView(camera_view);
        window.draw(text);

        window.display();
    }
    return EXIT_SUCCESS;
}

At the default resolution, it looks like this:

However, the moment I change the window size, we get artifacts:


texts:
I'm developing a top-down shooter in Java with Slick2D, and I've been ignoring this bug for a while because I'm not sure what causes it. I have numerous weapons that you can buy from the shop and cycle through using the scroll wheel or Q and E. The problem is that I've had a persistent bug where if you run out of ammo for one weapon, switch to another and try to fire, it will say you're out of ammo, even if the other weapon is full up. Then, after pressing reload for the second weapon, it will not let you fire the weapon. But if you then switch back to the weapon that was out of ammo and back again, it will allow you to fire.

I was wondering if someone could take a look at the logic for my weapon switching and reloading and tell me if there's a flaw in how it's being handled:

The following is the method that actually refills the clip, if there's any ammo left.

protected void reload() {
    int takeFromInv = getClipCapacity() - ammoInClip;
    int taken = Math.min(takeFromInv, ammoInInventory);
    ammoInInventory -= taken;
    ammoInClip += taken;

    reloading = false;
}

This is called during the update() method...

public void update(BasicGameState gs, long cTime, int delta) {
    // Basically just checking to see if the reload time has elapsed.
    if(reloading && !isReloading(cTime)) reload();
    ...

...once the reload timer has elapsed:

public boolean isReloading(long cTime) {
    long elapsed = cTime - reloadStart;
    return ((elapsed < getReloadTimeTotal()) && reloading);
}

The reload timer is kicked off when this method is called by the Player class when the 'R' key is pressed.

public void reload(long cTime) {
    if(getInventoryAmmo() > 0) {
        reloading = true;
        reloadStart = cTime;
        if(Talents.Munitions.HASTE.active()) {
            float roll = Globals.rand.nextFloat();
            if(roll <= 0.1f) {
                reload();
                StatusMessages.getInstance().addMessage("Haste!", Player.getPlayer(), Player.ABOVE_1, cTime, 1_000L);
            }
        }

        if(reloadSound != null) reloadSound.play();
    }
}

The method that determines if the weapon can be used (fired) is:

public boolean canUse(long cTime) {
    if(reloading) return false;
    boolean clipNotEmpty = ammoInClip > 0;
    boolean cool = (cTime - lastUsed) >= getTotalCooldown();

    if(!clipNotEmpty) return false;

    return (Player.getPlayer().isAlive() && equipped && cool && (automatic || release));
}

Finally, the weapon switching is handled in the Player class as such:

public void weaponRotate(int direction) {
    int wc = getRangedWeapons().size();
    if(wc > 0) {
        // have to use floorMod because apparently Java % is remainder only, not modulus... -_-
        int i = Math.floorMod((rangedIndex + direction), wc);
        setCurrentRanged(i);
    }
}

And here's the setCurrentRanged method:

public void setCurrentRanged(int wi) {
    List<RangedWeapon> weapons = getRangedWeapons();
    if(!weapons.isEmpty()) {
        if((wi >= 0) && (wi < weapons.size())) {
            // If the player actually has the weapon bound to the key that was pressed...
            getCurrentRanged().unequip();
            rangedIndex = wi;
            getCurrentRanged().equip();
        }
    }
}

And finally, getCurrentRanged():

public RangedWeapon getCurrentRanged() {
    List<RangedWeapon> weapons = getRangedWeapons();
    if(rangedIndex >= weapons.size()) return weapons.get(0);
    if(!weapons.isEmpty()) return weapons.get(rangedIndex);
    else return null;
}

I realize that's a lot of code to look over, but those are the relevant functions to my reload and weapon switching processes. I never realized it would be so difficult to implement a good, working reload system. So can anyone spot what might be causing this issue, or any other bugs that might pop up as a result of the way I implemented this?


texts:
I'm trying to make a croquet mallet swing to hit the ball using an animation that rotates the mallet mesh. The mesh appears correctly positioned to hit the ball in the center but the ball doesn't go straight. Using a script with rigidBody.AddForce works fine. I do have Animate Physics selected on the animator and have explored many other options. Is there a way to debug the physics in this situation? Am I going about it the wrong way to use an animation to apply a force?

This is what it looks like now:


texts: What would be a good way to implement a large 2d map?

texts:
I'm thinking of a way to implement a large 2d map which can be easy to handle a certain area of the map to update.
I've seen many 2d map using double array like
int[][] gameMap = {
{#,#,#,#,#},
{#,o,o,o,#},
{#,o,o,o,#},
{#,#,#,#,#}
};

However editing (fixing) the map by hand would be troublesome when it gets for example 1000*1000.

so what would be a good way to do so? I heard FF14 has a map uses grid to organize each small area.


texts: Modify Unity's New 2D Renderer for the Lighweight Render Pipeline

texts:
I would like to use the new 2D renderer available with the LWRP to take advantage of the 2D lights.

I would also like to replicate the things in this video - basically, I want my character to be visible through walls and when it is occluded.

The video uses the Forward Renderer to add the depth features, but there is no such thing in the properties of the 2D Renderer. Is it possible to both use the new 2D lights and use renderer features?


texts: In a 2D top-down game, how can I create projectiles that have a height?

texts:
A 2D game called Deer Hunter has projectiles like this:

Are the projectiles 2D or 3D models? How could I implement something similar?


texts:
As you know to draw a Texture2D mostly an Origin, scale-factor, rotation-value and color is necessary.

To inherite a new class ATexture2D from Texture2D with adding this parameters, can cause performance problems if many of them are called ?

Or what is prefered to do it in this case.

I ask this question for 2D games, where many texture2D objects are used, updated and drawn.


texts: Getting data from the backbuffer D3D11 using Map

texts:
I'm having some trouble using ID3D11DeviceContext::Map() correctly.
Here's the whole function so far:
 Color Graphics::GetPixel(int x, int y) const
{
    //Temp frame buffer descriptor;
    CD3D11_TEXTURE2D_DESC pFrameDesc;
    pFrameDesc.Width = WindowWidth;
    pFrameDesc.Height = WindowHeight;
    pFrameDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    pFrameDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    pFrameDesc.MipLevels = 1u;
    pFrameDesc.ArraySize = 1u;
    pFrameDesc.SampleDesc.Count = 1u;
    pFrameDesc.SampleDesc.Quality = 0u;
    pFrameDesc.Usage = D3D11_USAGE_DEFAULT;
    pFrameDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
    pFrameDesc.MiscFlags = 0u;

    // Create temp frame buffer(2d texture)
    wrl::ComPtr<ID3D11Texture2D>pFrame = nullptr;
    HRESULT hr = pDevice->CreateTexture2D(&pFrameDesc, nullptr, &pFrame);
    GFX_THROW_INFO(hr);

    hr = pSwapChain->GetBuffer(0, __uuidof(pFrame), &pFrame);
    GFX_THROW_INFO(hr);

    D3D11_MAPPED_SUBRESOURCE map;
    map.RowPitch = WindowWidth * 4;
    map.DepthPitch = WindowHeight * 4;

    //Throwing here, CPU access flags problem.
    hr = pContext->Map(pFrame.Get(), 0u, D3D11_MAP_READ, 0u, &map);
    GFX_THROW_INFO(hr);

    pContext->Unmap(pFrame.Get(), 0u);

    return { 0.0f, 0.4f, 0.0f, 0.0f };
}

I'm getting an exception thrown at pContext->Map()
"Map cannot be called with MAP_READ access, because the Resource was not created with the D3D11_CPU_ACCESS_READ flag. "
Which is confusing as the newly created resource has the D3D11_CPU_ACCESS_READ flag enabled. This is also true If I try MAP_WRITE and change the access flags to match. I've also tried ORing the flags together with no luck.
The ultimate use of this function is to be able to create a CPU side array of Color objects (Colors are currently a struct of four floats) Which I can then send onto the NewTek NDI sdk. But I feel it would also be useful for saving screen shots, creating colour pickers etc.
Any ideas welcome!


texts:
I making a small steering simulator using the Reynolds boid algorithm.
Now I want to add a wall avoidance feature. My walls are in 3D and defined using two points like that:

   ---------. P2
   |        |
P1 .---------

My agents have a velocity, a position, etc...

Could you tell me how to make avoidance with my agents?

Vector2D ReynoldsSteeringModel::repulsionFromWalls()
{
    Vector2D force;
    vector<Wall *> wallsList = walls();
    Point2D pos = self()->position();
    Vector2D velocity = self()->velocity();

    for (unsigned i=0; i<wallsList.size(); i++)
    {
        //TODO
    }

    return force;
}

Then I use all the forces returned by my boid functions and I apply it to my agent.

I just need to know how to do that with my walls.

Thanks for your help.


texts: Do opengl games tend to use multiple shaders?

texts:
For any given object that you want to render, there may be a whole bunch of things that need to be considered for rendering (Material, Texture, Lighting, Blending etc). But, you may also have some objects which are very simple, and do not have a Texture or material or require any blending and ignore lights.

So, how do people approach this. Do you write one GLSL shader that has various booleans and checks that need to be set as vertices are pumped through, or do you write separate shaders for each general category of object, and switch between these as your render?


texts: Unity5 UI - How to trigger button click event while preventing menu item deselect event?

texts:
So I've got a load menu using Unity's new UI system, basically just a list of save games you can select with a mouse click along with a couple of buttons at the bottom to delete or load the selected game file.

I've been disabling the Load Game and Delete Game buttons using the interactable attribute whenever a saved game item in the list is deselected:

deleteButton_LoadPanel.GetComponent<Button>().interactable = false;
loadButton_LoadPanel.GetComponent<Button>().interactable = false;

This disables the buttons fine, but when I click on a saved game and then click a button, the deselect event for each save file is triggered BEFORE the onclick event for each button. This is no good.

If I have no deselection event for each individual save file I can click on each save file and then click the load or delete buttons and every thing works fine, but the buttons never get disabled which is not ideal.

My question is:
How can I disable the buttons when an item is deselected, but still trigger the onclick event when they are selected? Are there any workarounds to this?


texts:
I have a game that calculates your score via Time.deltaTime (the more time the more score). On my PC I get about 1200 points if I just idle the game while on my phone I only get about 400 points.

I believe my code must be FPS dependant and that's why my phone is getting a lower score for the same time.

Here's the code:

void Update ()
{
    time += Time.deltaTime;

    score += (int)time;

    timerLabel.text = score.ToString();
}

Sorry if it's something very obvious. I'm quite new at c#.

Can't seem to get the solution to work. It just stays at 0:

Full Code:

    using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class EndGame : MonoBehaviour {

    public Text textWin;
    public Text timerLabel;
    public GameObject retryButton;
    public GameObject points;

    private Vector3 offset;
    private float time;
    private float score;

    void OnTriggerEnter (Collider col) {
        if (col.gameObject.name == "Player") {
            setWinText ();
            retryButton.SetActive (true);
            points.SetActive (false);
        }
    }

    void setWinText () {
        textWin.text = "Final score: " + score.ToString();
    }

    void Update ()
    {
        time += Time.deltaTime;
        if (time >= 1.0f) {
            ++score;
            score -= 1.0f;
        }

        timerLabel.text = score.ToString();
    }

}


texts: In Godot 3.2.1 stable beta, in the 2D sprite shaders, how do I import a new PNG to test out those shaders?

texts: I am using Godot 3.2.1. on Steam on Linux Mint. How do I take a pixel art image I've made and import it for using in Godot? I couldn't find it under Project.


texts: JBullet - How can I make my object float on the water?

texts:
I'm trying to use JBullet for a ship PVP game.

I've got two ships which are meant to rest on the water. Obviously these ships will be colliding, but the problem I have currently is "water" collision.

Water cannot be a "solid" object, and I cannot work anything out that will allow it to have the ship resting in it without falling over or having some sort of speed dampening effect.

Also, the ships keep being launched upwards or downwards depending on the collision. The problem here is that I cannot set a weight for the ships, because if I did, they would currently be sinking into what JBullet believes to be nothingness.

How would I simulate water in this collision world?


texts: Creating blur with an alpha channel, incorrect inclusion of black

texts:
I'm trying to do a blur on a texture with an alpha channel. Using a typical approach (two-pass, gaussian weighting) I end up with a very dark blur. The reason is because the blurring does not properly account for the alpha channel. It happily blurs in the invisible part of the image, whcih happens to be black, and thus results in a very dark blur.

Is there a technique to blur that properly accounts for the alpha channel?


texts:
I have a Coroutine that I use to pull and spawn an enemy in my game. This coroutine works perfectly fine, with the exception of the very first call. I am fairly certain this is because I am probably loading something before it is ready, but I don't know enough to know where.

This is my code (Note the Debug.Log entries). I have removed whatever I think is irrelevant code.

EnemyHandler.cs

public class EnemyHandler : MonoBehaviour
{
public int mob_id;
IEnumerator LoadMob()
{
    Debug.Log("Checkpoint 1");

    WWWForm form = new WWWForm();
    form.AddField("mob_id",mob_id);
    WWW www = new WWW("my-url-here",form);
    yield return www;
    Debug.Log("@@@@@@ Checkpoint 2 @@@@@@");
    string[] webResults = www.text.Split('\t');

    int returncode = int.Parse(webResults[0]);

    switch (returncode)
    {
        case 0:
        //Mob Loaded Successfully
        //Mob variables are set here
        Debug.Log("@@@@@@ Checkpoint 3 @@@@@@");
        break;

        default:
        Debug.Log("Error!");
        break;
    }

}

 public void CallMobLoad(int requested_mob_id)
 {
     mob_id = requested_mob_id;
     StartCoroutine(LoadMob());
     Debug.Log("Coroutine called! Checkpoint 0");
 }
}

2.GameManager.cs (This is my primary class)

public class GameManager : MonoBehaviour
{
    public GameObject spawnManager;
    public static EnemyHandler thisenemy;

    void Start()
    {
     thisenemy = spawnManager.AddComponent<EnemyHandler>();
     thisenemy.CallMobLoad(1);
    }
}

CallMobLoad is called once at Start, and every time a monster dies. It never works when called in Start(), but always works after that.

Furthermore, the first call only calls the first 2 Debug.Logs "Checkpoint 0" and "Checkpoint 1", none of the other checkpoints are hit. Every subsequent call works correctly and hits all checkpoints.

I really want to learn how/why this happens, Any help is greatly appreciated!

EDIT: I have fixed this by turning Start into an IEnumerator, and adding a yield return to thisenemy.CallMobLoad(mobloadtemp);

Still not sure if this is the best way to do this, so please do advise.


texts: How do I prevent buffered image size fluctuation when rotating?

texts:
As you can see in the GIF, as the car rotates, as the Car rotates, the size appears to change to fit the determined height and width, what would be the best way to change these in conjunction with the rotation. I have rotation saved as a variable from 0 to 359. I am using affine transform and a buffered image in Graphics2D. Is there an easy way to fix this in affine transform or when rendering?
rotator
public BufferedImage rotateImageByDegrees(BufferedImage img, double angle) {

        double rads = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads));
        int w = img.getWidth();
        int h = img.getHeight();
        int newWidth = (int) Math.floor(w * cos + h * sin);
        int newHeight = (int) Math.floor(h * cos + w * sin);

        BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();
        AffineTransform at = new AffineTransform();
        at.translate((newWidth - w) / 2, (newHeight - h) / 2);

        int x = w / 2;
        int y = h / 2;

        at.rotate(rads, x, y);
        g2d.setTransform(at);
        g2d.drawImage(img, 0, 0, null);
        g2d.dispose();

        return rotated;
    }

rendering
        g.drawImage(handler.rotateImageByDegrees(img, Direction), (int) x, (int) y, (int) width, (int) height, null);


texts:
I am working on a small tactical game like X-com.
I now have a working-ish version and would like to treat myself to some aesthetic upgrades!
I have been thinking hard about the following but I can't seem to figure out how to "nicely" highlight the edge of my movement range.
I would be looking for something like this:

As you can see the mesh range is highlighted with smooth corners.
At the moment the best I have managed is to simply instantiate a "tile" prefab at the correct locations:

This leads to all kind of funky artefacts like the fact that the range gets hidden behind any objects. In the following image the character can actually move onto the wooden porch but the tiles are instantiated below it (see red circled area):

I suspect a shader approach where the range is projected onto the camera might be a better approach...  I could then add a shading to the bits of the range behind objects whilst still showing it. Problem is I have no idea how to go about it, and couldn't find any tutorial online.
Help most welcome!


texts:
Currently I'm making a voxel survival game. About a month ago I embarked on procedurally generating terrain using Perlin noise. I understand how to use and apply it for the most part. However I do not understand how to vary terrain structure. Let me say that in a way you probably can understand because "me no grammar good".

By changing frequency and amplitude I know I can change the resulting terrain, varying it from rolling hills to jagged peaks. However the end result will always be the same: either never ending hills or never ending mountains. I don't understand really how I would mix those two "terrain structures" together to get area's of hills and area's of mountains.


texts: How can I convert a List to Transform[] array?

texts:
var selection = Selection.objects.OfType<GameObject>().ToList();
tempTransforms = selection;

selection is List and tempTransform is Transform[]
And I want to assign the selection to the tempTransform.


texts: Overridden movement function doesn't work

texts:
I moved from C to C# so I am a novice in Object Oriented Programming. I wanted to implement OOP in my character movement, but it didn't work the way I expected.
My character is instantiated when the scene starts, but it doesn't move (maybe because of bad parameter passing).
I just want to control input from derived class which is giving my character the ability to sprint.

characterB script is attached to character in Inspector
that character is instantiated prefab and is instantiated when scene start
inherited script which is overridden is giving ability to sprint to character
photon is package for multiplayer games so you don't have to notice it

whole source code is so big, so i put there one method for movement
and sorry for my weak english skillz
 //works like standard MonoBehaviour
public abstract class characterMain : MonoBehaviourPunCallbacks
{

    // declaration of variables

    public virtual void Start()
    {
        RB = GetComponent<Rigidbody>();
    }

    protected virtual void movement(float horXF, float vertYF, bool sprintB)
    {
        //Debug.Log("movement function base class" + horF); // NOT responding
        groundDetect = Physics.Raycast(...);

        if (standOnGround)
        {
            direction = new Vector3(horXF, 0, vertYF) * Time.deltaTime * speed;

            direction.Normalize();
            adjustSpeed = speed;
            targetSpeed = transform.TransformDirection(direction) * adjustSpeed * Time.deltaTime;
            RB.velocity = targetSpeed;
        }
    }
}

public class characterB : characterMain
{

    [Header("Movement")]
    protected float horXF;
    protected float vertYF;
    [Header("sprint")]
    private bool sprintB;

    public void FixedUpdate()
    {
        if (!photonView.IsMine) return; //Photon

        //MOVEMENT INPUT
        horXF = Input.GetAxisRaw("Horizontal");
        vertYF = Input.GetAxisRaw("Vertical");
        //JUMP INPUT
        skokB = Input.GetKey(KeyCode.Space);

        movement(horXF, vertYF, sprintB);

        //Debug.Log("movement function" + horF); //responding
    }

    protected override void movement(float horXF,float vertYF,bool sprintB)
    {
        //Debug.Log("movement function" + horF); // NOT responding

        if (sprintB && ... ) //sprint
        {
            base.movement(horXF, vertYF, sprintB);

            sprintB = bZrychlenieC && groundDetect && ... ;
            if (sprintB) direction = new Vector3(0, 0, sprintSpeed) * Time.deltaTime;
        }
    }
}


texts:
I have a textfield using scene2d but don't know how to save user input. this is what i have and it just draws the textfield.

     txtUsername = new TextField("", mSkin);
     txtUsername.setMessageText("test");
     txtUsername.setPosition(30, 30);
     mStage.addActor(txtUsername);


texts: How can I make a tile appear on top of another without completely blocking the tile below?

texts:
Making a small RPG with libdgx just for learning about how to draw tiled maps and move around in them.  I've got the tiles drawn and OrthographicCamera stuff figured out so I can see my world.  My question is, how can I put character on a tile, so that he appears to be standing on the tile?

My idea is to give each tile a separate texture that has the character drawn on the tile.  So for example, I would have grass.png and then I would have grass-hero.png.  And then based on where the hero is upon the next render loop, if the hero has moved to a tile that was previously "grass", instead this time draw "grass-hero".

Example:

Now, I haven't done it yet, but I'm pretty sure that would work.  My question is, is there some way that I can bypass having to use a separate "combined" tile like grass-hero, and just have my hero walk on top of the grass tile?  I imagine if I use another tool like .NET Paint I could "cut" the hero out of the black background and make the background transparent, but I still don't know how to make one tile appear on top of another.

To provide some abbreviated semi psuedo code, let me show what I have:

GameScreen (implements Screen)

@Override
public void render(float delta)
{
    worldrenderer.render();
}

WorldRenderer

public void render()
{
    spriteBatch.begin();
    drawTiles();
    drawHero();
    spriteBatch.end();
}

private void drawTiles()
{
    for (Tile tile : world.getTiles())
    {
        switch(tile.getTileType())
        {
             case GRASS:
                 spriteBatch.draw(grassTexture, tile.getPosition());
                 break;
             case FOREST:
                 spriteBatch.draw(forestTexture, tile.getPosition());
                 break;
             case STONE:
                 spriteBatch.draw(stoneTexture, tile.getPosition());
                 break;
        }
    }
}

private void drawHero()
{
    Hero hero = world.getHero();
    spriteBatch.draw(heroTexture, hero.getPosition());
}


texts: How to mark a variable as prefab independent?

texts:
I am making a game that has a symmetrical level design. Each player own a portion of the map and each portion is the same. As such, I placed the portion as a prefab so that when I apply the prefab, every other portion gets changed as well.

On the prefab there is a script. This script contains a variable called playerId. I dont want this variable to change to prefab default when I apply the prefab. Is there an attribute tag I can use to do this? As far as I am aware, Unity's transform.position doesnt get affected by the prefab defaults.


texts: My "puck" model object falls right through the "table" model in jMonkeyEngine

texts:
So I am trying to learn jMonkey, I have understood everything so far, and I thought I understood how to make objects solid, so things can't go through each other. When I create my Collision shapes, I turn on the debugger which shows the shapes, and they appear correct. But when I run the code the puck falls right through the table and I have no idea why? I have been trying to learn from http://wiki.jmonkeyengine.org/doku.php/jme3:beginner:hello_collision.

public class Main extends SimpleApplication {

    public static void main(String[] args) {
        Main app = new Main();

        AppSettings settings = new AppSettings(true);
        settings.setResolution(1024,768);
        settings.setFrameRate(60);
        app.setSettings(settings);

        app.start();
    }

    private BulletAppState bulletAppState;

    private RigidBodyControl    table_phy;
    private RigidBodyControl    puck_phy;

    @Override
    public void simpleInitApp() {

        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.getPhysicsSpace().enableDebug(assetManager);

        DirectionalLight sun = new DirectionalLight();
        sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f).normalizeLocal());
        rootNode.addLight(sun);

        cam.setLocation(new Vector3f(0.0f, -2.0f, 7.0f));

        initTable();
        initPuck();
        initPusher1();
        initPusher2();

    }

  //My hockey table
    public void initTable() {
        Spatial table = (Node)assetManager.loadModel("Models/airTable/airTable.j3o");
        table.setLocalTranslation(0.0f, -5.0f, -2.0f);
        CollisionShape tableShape = CollisionShapeFactory.createMeshShape((Node) table);
        table_phy = new RigidBodyControl(tableShape,0.0f);
        table.addControl(table_phy);
        rootNode.attachChild(table);
        bulletAppState.getPhysicsSpace().add(table_phy);
    }

    //My puck
     public void initPuck(){
        Spatial puck = assetManager.loadModel("Models/puck/puck.j3o");
        puck.setLocalTranslation(1.0f, -3.0f, 0.0f);
        CollisionShape puckShape = CollisionShapeFactory.createMeshShape((Node) puck);
        puck_phy = new RigidBodyControl(puckShape, 0.05f);
        puck.addControl(puck_phy);
        rootNode.attachChild(puck);
        bulletAppState.getPhysicsSpace().add(puck_phy);
    }
}


texts: Is making an acceptable 3D engine possible using only SDL_* functions?

texts:
I've been watching Javidx9's 3D engine series and I decided to start making it with SDL because it was something I had heard of and seemed simple enough. I'm not going to implement too complex graphical features anyway. So I start writing code, and I'm drawing my triangles with SDL_DrawLine(), and I'm filling my triangles with SDL_DrawLine, and I go to load up the Utah Teapot and the frames are stuttering quite a bit. I'm pretty sure I already know the answer to this question but I want to be sure: Is it unrealistic to try to create a 3D engine without using raw OpenGL funcions? It would make sense that the frames are so bad because SDL would have to work through something like OpenGL so I'm just calling an abstracted DrawLine function that's just making the computer do extra stuff and slowing it down.

By the way, I do know that SDL has OpenGL, but I (naively?) figured it would just be easier to go without it.


texts: Unity Grid Layout causing multiple draw calls

texts:
We are developing a game in Unity 4.6.6 for both Android and iOS.

Currently I am building the game UI with the new Unity UI system. In particular I am building a button list to create kind of inventory slots using the Grid Layout.

I have noticed that my draw call count is increasing considerably despite having my UI in an atlas (using Sprite packer) and using the same font all over the UI.  After some tests I noticed that one draw call is generated per each UI Text and UI image present in the scene composing each button when using a Grid Layout Group, when the Grid Layout is not used the draw calls are reduced noticeably.

7 elements without Grid Layout, results in 2 draw calls:
(Screenshots taken in play mode)

7 elements WITH Grid Layout, resulting in 14 draw calls:
(Screenshots taken in play mode)

I have no idea if it is possible to reduce the number of draw calls when using the Grid Layouts.


texts: What Java library provides a high-level communication interface suitable for use in an action-game server?

texts:
I need to write a server for an action game, which needs fast communication with the client. There will only be one server, and I'll split the world in zones. The client will be written in Java using jMonkeyEngine and in my opinion I should write the server in Java as well. I don't want to implement any low-level features such as communication, reliable udp, etc.

Is Java the most appropriate language to write an action game server which will run on Linux? Is there a Java library which provides a high-level interface for network communication?


texts:
So I have a sprite of an ellipse ( it is a 2D game). I would like to get a point inside this ellipse so I can instantiate something. How would I do that? Sprite won’t be changing the scale, so uniform scale.

The point shouldn’t be on the edge and a bit further away from the edge


texts: Is it worth supporting iOS 3.x or iPhone 3G devices anymore when developing a game?

texts:
Is it still worth it for a game developer to try and support older devices: iPhone 3G and earlier or to support older OS: iOS 3.x and earlier?
Or is it recommended to make use of OpenGL ES 2.0 supported be the iPhone 3GS and above?
Do you know what percentage of users still use those earlier version of devices/operating systems?


texts: How can I test my game for epilepsy-safety?

texts:
I've been developing a game which is rather blinky in terms of color and brightness contrasts.  It's an iPhone game, so the screen will be quite small, but I've heard about Wipeout XL failing the epilepsy test.

How does one ensure that a game won't cause epileptic seizures for users?

I am an indie developer, so a low-budget solution would be ideal.


texts:
I have found that Stencyl doesn't seem to be very good at handling very many actors in a game. I had been trying to implement some basic AI at the moment all the behaviours were: wander (pick a random point and move directly to it) and wrap around screen (if it goes off the top of the screen it appears at the bottom). Even with these simple behaviours and calculations the frame rate dropped dramatically when there were more then 50 actors on screen:

10 actors: 60fps

50 actors: 30-50fps

75 actors: ~30fps

100 actors: 15-20fps

200 actors: 8-10fps

I had planned on having a maximum of around 200 actors but I see that's no longer an option and implementing a more complicated AI system with flocking behaviour, looking at creating a game in a similar vein to flOw.

I understand that a game is perfectly playable at 30fps but this is a super simple test with ultra simple graphics, no animations and no sounds is child's play in terms of calculations to be made.

Is this a limitation with Stencyl or is it flash?
Should I simply scale the scope of the game down or is there a better game engine that exports to .swf that I should look into?


texts:
I have the following scene canvas elements:

 left panel
     character game object
 right panel
     option panel - vertical layout group, content size fitter
         slider panel - vertical layout group, content size fitter
             input panel - horizontal layout group, content size fitter
                 text
                 slider
             input panel - horizontal layout group, content size fitter
                 text
                 slider
         button

After I hit play, the button's Y position is wrong but corrects itself after a brief second. Why is this happening and how do I fix it?

Here is a gif:


texts: How to calculate a projection of 360° equirectangular slides?

texts:
My goal is to have a light source inside of a transparent sphere that has an equirectangular texture to act as a 360°-slide. I want to get the projection on arbitrary objects as a texture image on these objects in high resolution. This will happen on a webserver.

So my input should be the equirectangular and the object and optionally position of the light source and my output should be texture files of each flat surface of the arbitrary object.

What algorithms can I use to make this as simple, quick and fast-in-action as possible?


texts: Tips for building an AI for a 2D racing game

texts:
I have a school project to build an AI for a 2D racing game in which it will compete with several other AIs (no collision).

We are given a black and white bitmap image of the racing track, we are allowed to choose basic stats for our car (handling, acceleration, max speed and brakes) after we receive the map. The AI connects to the game's server and gives to it several times a second numbers for the current acceleration and steering. The language I chose is C++, by the way. The questions are:

What is the best strategy or algorithm (since I want to try and
win)? I currently have in mind some ideas found on the net and one or
two of my own, but I would like before I start to code that my
perspective is one of the best.
What good books are there on that matter?
What sites should I refer to?


texts: Developing an interactive book for Windows-Runtime

texts:
My three year old loves playing with the interactive books on our iPad, and I love playing with code and I love my Surface RT...

So I thought I'd try and make a basic animated book using WinRT, I've spent some time reading about animations
(granted the book isn't WinRT based), and thought I'd try and use the Storyboard approach rather than rolling any kind
of bespoke animation framework.

That was until I saw the Faresee Physics Engine, and the Physics XAML Helper.

I've played around with some of the more basic examples, and it seems pretty good - very easy in-fact.

My issue is when I start thinking about stringing together animations that can react to input,
the Farsee and Physics XAML Helper blows my mind a little.

As a proof of concept I was thinking about getting a character to walk from a path (in the top right),
and while moving closer (getting larger) walk to the front at the center.

Then, based on some kind of decision, via an input, walk either back to the right, or up to the left.
Both are back into the distance (getting smaller) as if walking away.

The character should have basic humoid movement, athough slightly cartoon-like - swinging arms, moving head and legs.
Also, it would be nice to have the ability for the character model to swap images when it walks back up the path.

My question (finally!), is do you think that it's better to use the built in Storyboarding features of WinRT, with it's
animations - primarily using easing and descrete key frames to create each animation 'scene'. Or, use something like
Farsee and the Physics XAML Helper to create the scene using real word objects and physics?

Are there any examples, samples, tutorials etc of creating anything similar?

Thanks,
Kieron


texts: Changing a single component of a prefab?

texts:
I'm working on a unity project and I'm looking to show the range of a certain character.

However, the terrain is generated through a script at run time, and considering that the script uses the same prefab for each tile, any modification made to one prefab affects the others as well.

Hence, I'm looking for a method in which I can independently tweak the settings of each prefab. The unit in question is to shoot a ray-cast to determine which tile it is on, and a script would then modify the colour of the neighboring tiles so as to determine the range of the unit.

Any advice on how to achieve this will be highly appreciated.


texts: UDK problem with kismet and unreal code interfacing

texts:
Couple of questions that I really have looked for the answer to before posting.

I want to create enemies in a game (iOS - tower defense like) I am making them follow a path and do other things like die etc..

I created a simple piece of code to make a place-able enemy in my level but this is the thing I don't know what the best way to continue is. I want to create enemies in code rather than placing in game and therefore I do not know how to assign the kismet path to each one?

My mobile material isn't working even though I made the material have a mobile texture? Works in PC not in mobile preview.

Thanks in advance.
Mike

Class BlobzEnemyGround1 extends BlobzEnemy
placeable;

simulated function PostBeginPlay()
{
    super.PostBeginPlay();
    `log("Blobz Enemy Ground 1 spawned!");
}

defaultproperties
{
    bBlockActors=True
    bCollideActors=True

Begin Object Class=DynamicLightEnvironmentComponent Name=MyLightEnvironment
    bEnabled=TRUE
End Object
Components.Add(MyLightEnvironment)

Begin Object Class=StaticMeshComponent Name=PickupMesh
    StaticMesh=StaticMesh'UN_SimpleMeshes.TexPropCube_Dup'
    Materials(0)=Material'Level1.TestEnemyMat'
    LightEnvironment=MyLightEnvironment
    Scale3D=(X=0.25,Y=0.25,Z=0.5)
End Object
Components.Add(PickupMesh)

Begin Object Class=CylinderComponent Name=CollisionCylinder
    CollisionRadius=32.0
    CollisionHeight=64.0
    BlockNonZeroExtent=true
    BlockZeroExtent=true
    BlockActors=true
    CollideActors=true
End Object
CollisionComponent=CollisionCylinder
Components.Add(CollisionCylinder)
//bSupportedOnMobile=true;

}


texts:
I am working on a tile based game on a globe. I am trying to implement a simple day night cycle on my hex globe something similar to the image below

Here is the picture of my globe inside Unity

I am just using a few point lights but it doesn't look perfect. Would it be possible to do better with the current lighting system in Unity or do I have to just play around with different lights, intensity and their positions to make it look close to what I want. Also is there any way through a script that I can get information on if my gameobjects in the scene are being lit by a source of light. I would want this to get information on the tiles that are in the dark and the ones that are in the light


texts: When attempting to open an old project or create and open a new project unity won't open. The hub will open and when you choose a project it will close and then nothing will happen. Also when a new project it will state the unity version for the new project as unknown. I have tried uninstalling, deleting all the files under the registry editor, and also removing the files from the appdata and reinstalling and it doesn't appear to fix it. Does anyone have any suggestions on how I can fix this?


texts: How do you create hitboxes that will detect stationary targets too?

texts:
I've created a basic attack combo system that chains 3 attacks together.

When the player clicks the mouse button, it enables a boxCollider2D attached to the player.

The boxCollider is a trigger and will cause damage to a valid target using OnTriggerEnter2D.

This doesn't seem to be very responsive, and often will not work if the target is stationary. I've thought about trying Raycasts as an alternative but am looking for advice on how to handle this properly.

public class Attack : MonoBehaviour
{
     private int comboIndex;
     public float lastAttack;
     private Animator _animator;
     private string[] attackName;
     private float comboResetTimer;
     private BoxCollider2D _hitbox;

     private void Awake()
     {
         attackName = new[] {"Attack1", "Attack2", "Attack3"};
         _animator = GetComponent<Animator>();
         _hitbox = GetComponent<BoxCollider2D>();
     }

     private void Update()
     {
         var canAttack = Input.GetMouseButtonDown(0);

         if (canAttack && comboIndex < attackName.Length)
         {
             _animator.SetTrigger(attackName[comboIndex]);

             _hitbox.enabled = true;
             comboIndex++;
             comboResetTimer = 0f;
         }

         if (comboIndex > 0)
         {
             comboResetTimer += Time.deltaTime;
             if (comboResetTimer > lastAttack)
             {
                 _animator.SetTrigger("Reset");
                 comboIndex = 0;
                 _hitbox.enabled = false;
             }
         }
     }
 }


texts: Creating a "world" for evolution of programs

texts:
I am trying to create a "world" where "copies of programs" are allowed to evolve, proliferate and fight for resources.
Organisms copy information with errors and memorize the results. It seems like one can create a "world" with resources, place various copies of a program and let them fight for resources, grow and evolve.

What would it be for Java programs. World has cells each producing certain amount of letters per tic.  An organism is a String of text that extends Life, compiles correctly, has methods eat, move and breed. Every tic move, eat, breed are executed. On move organism can decide to move to nearby cell. On eat it can move all free letters from cell to it's body (store those behind /* here */ to make sure program compiles). During breed stage it it can build it's own copy using letters from the commented area of the program body. Copying is error prone. If the resulting copy compiles it joins the race for resources.

Here are the problems I am having:
A single character change in a program tends to cause compile time error. How to increase survival chances of an offspring with a point mutation?
IRL organisms eat each other. How to model predator attacking prey? Some simple injectPoison(prey); that injects */ between 50th and 51st characters in the body of prey string would kill pretty much any program. Something like "to fight: run Robocode - winner gets all loser's letters" would turn the world into a Robocode engine competition.
IRL organisms do exchange information. One can allow programs to exchange their methods, but then it is very tempting for a program to just inject a suicide method and eat the body of dead partner.

My questions are:
Is there any research on building such world? What is the best way to model resources? What limits the extent of evolution in such models.


texts: What's the best way to compare blocks in a matching game that can be multiple colors?

texts:
I have a match 3-4 game and the blocks can be one of 7 colors. There are an addition 7 blocks that are a mix of the original 7 colors so for example there is a red and blue block and there is also a red/blue block which can be matched with either the red or the blue. My original thought is just to use binary operations so.

int red     = 0x000000001;
int blue    = 0x000000010;
int redblue = 0x000000011;

Then just do an & operation so see if they match. Does this sound like a decent plan or am I over complicating it?

edit:

Better yet so it's more readable.

int red = 1;
int blue = 2;
int red_blue = 3;
int yellow = 4;
int red_yellow = 5;

maybe as defines or static vars?


texts:
I want to generate a terrain which looks like hills. Some sort of sine waves. Should be as simple as possible. But I can not figure out how. I get very scary results, which are nothing worth. I need to have vertices, normals and the indices of the vertices.

for(int i=0; i < size; i++) {
for(int j=0;j < size; j++) {
verticesList.add((float) j);
verticesList.add((float)Math.sin(j) * 1.5f);
verticesList.add((float) i);

normalsList.add((float) j);
normalsList.add((float)Math.sin(j) * 1.5f);
normalsList.add((float) i);

indicesList.add((byte)(i+j));

verticesList.add((float) j);
verticesList.add((float)Math.sin(j) * 1.5f);
verticesList.add((float) i+1);

normalsList.add((float) j);
normalsList.add((float)Math.sin(j) * 1.5f);
normalsList.add((float) i+1);

indicesList.add((byte)(i+j + 1));
}
}

I know that this is not the way how normals a "calculated".

P.S.: I need something like this:

edit:

How do I compute the normals?


texts: How to increase points per second when speed increases

texts:
I am making an endless rider game that is crossed between tron legacy and cube field. I am trying to add a point system were the faster you go the more points you get because you are more likely to die so high risk high reward. I am really stuck on this however. This is my current script which is already connected to a point ui system that works. I am also probably going to post a question later about how to make speed correlate with emission/light intensity.

 public static int movespeed = 1;
    public Vector3 userDirection = Vector3.right;

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Input.GetAxis("Horizontal") * Time.deltaTime * 50, 0f, Input.GetAxis("Vertical") * Time.deltaTime * 70, 0f);
        transform.Translate(userDirection * movespeed * Time.deltaTime * 40);
        scorecript.scoreValue += 10;

        if (Time.deltaTime > 10)
        {
            scorecript.scoreValue += 10;

        }
        if (Time.deltaTime > 11)
        {
            scorecript.scoreValue += 11;

        }

    }

This is how I translated MDgrgory's code:

[Tooltip("How fast the character should move with no input, in world units per second")]
public float autoMoveSpeed = 40.0f;
[Tooltip("The direction the character should move with no input")]
public Vector3 autoMoveDirection = Vector3.right;
// Enforce that this is always a unit direction vector, so it doesn't bias our speed.
void OnValidate() { autoMoveDirection = autoMoveDirection.normalized; }

[Tooltip("How much the player can affect the speed in the direction of auto movement")]
public float parallelMoveSpeed = 50f;
[Tooltip("How fast the player can affect the speed perpendicular to the auto movement")]
public float perpendicularMoveSpeed = 70f;

[Tooltip("How many points to earn per second with no input")]
public float scorePerSecondAtDefaultSpeed = 10f;
[Tooltip("How many extra points to earn per second for every extra unit of speed")]
public float extraScorePerVelocityUnit = 1.0f;

// Track how much "loose change" points we've accumulated.
float _scoreAccumulator = 0f;

void Update()
{
// Capture the player's input vector.
Vector3 input = new Vector3(
                    Input.GetAxis("Horizontal"),
                    0,
                    Input.GetAxis("Vertical")
                );

// Clamp the input to make sure we don't move faster on diagonals.
input = Vector3.ClampMagnitude(input, 1.0f);

// Extract the portion of the player's input parallel to the auto movement.
float parallelComponent = Vector3.Dot(autoMoveDirection, input);

// Leaving the component perpendicular to the auto movement.
Vector3 perpendicularComponent = (input - parallelComponent * autoMoveDirection);

// Compute how much to increase or decrease our auto movement based on our input.
float extraVelocity = parallelComponent * parallelMoveSpeed;

// Compute our net velocity, combining auto, parallel, and perpendicular movement.
Vector3 velocity = autoMoveDirection * (autoMoveSpeed + extraVelocity)
                 + perpendicularComponent * perpendicularMoveSpeed;

// Translate us according to that velocity and the elapsed time.
transform.Translate(velocity * Time.deltaTime, Space.Self);

// Scoring:
// Compute our increased (or reduced) scoring rate based on our forward velocity.
float extraScore = extraVelocity * extraScorePerVelocityUnit;

// Increase our score accumulator based on our current earning rate and time passed.
_scoreAccumulator += (scorePerSecondAtDefaultSpeed + extraScore) * Time.deltaTime;

// Whenever we earn a whole point, send it to the score display as an integer.
int scoreUnits = Mathf.FloorToInt(_scoreAccumulator);
scoreScript.scoreValue += scoreUnits;
// And decrement our accumulator to store just the "spare change".
_scoreAccumulator -= scoreUnits;
}


texts: Problem reseting device when using render target

texts:
How can I reset the device when I am rendering to a surface, and then stretching that surface to the back buffer. If i don't change the render target everything goes well, but when i change the render target(only once when the game starts), i get D3DERR_INVALIDCALL. What do i have to do to stop getting this error. I've tried to set the render target back to the backbuffer, and then after resetting the device back to the surface but it didn't work.

EDIT:

HRESULT result;

initD3Dpp();
sprite->OnLostDevice();

device3d->SetRenderTarget(0, oldSurface);

if(oldSurface) oldSurface->release();
SAFE_RELEASE(surface);

result = device3d->Reset(&d3dpp);

device3d->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
device3d->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
device3d->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

device3d->CreateRenderTarget(GAME_WIDTH, GAME_HEIGHT, d3dpp.BackBufferFormat, d3dpp.MultiSampleType, d3dpp.MultiSampleQuality, false, &surface, NULL);
device3d->GetRenderTarget(0, &oldSurface);
device3d->SetRenderTarget(0, surface);

sprite->OnResetDevice();

return result;


texts: Having trouble with foreach loop affecting anything past the first object found

texts:
I have been trying to disable isTrigger in unity c# script on all GameObjects containing a certain tag. Currently my code works and disables the isTrigger part of the box collider, but it only does this for the first object with the tag I am looking for do this for all objects.

Here is the code:

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

public class DefenseCollisionTrigger : MonoBehaviour {

    public static Rigidbody rb;
    public bool CanBePlaced;
    public GameObject[] defenseTriggers;

    void Start ()
    {
        CanBePlaced = true;
        defenseTriggers = GameObject.FindGameObjectsWithTag("Defense");
    }

    public void OnTriggerEnter (Collider other)
    {
        if (other.tag == "Defense")
        {
            CanBePlaced = false;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        if (other.tag == "Defense")
        {
            CanBePlaced = true;
        }
    }

    public void IsTriggerFalse()
    {
        foreach (Object dt in defenseTriggers)
        {
            Debug.Log("working on it");
            GetComponent<Collider>().isTrigger = false;
        }
    }
}

That is what is currently looks like. The public void IsTriggerFalse() is called on each time I go to instantiate an object with my mouse button. The Debug.Log is working and printing to the console. This is the closest I have came to making it work, but it only works for the first object. I have searched for hours and watched videos/looked at unity docs on foreach statements with no luck to my issue. I have also tried using foreach (GameObject dt in defenseTriggers) instead of just Object.

Anyone know how to solve my issue?


texts: Why do separate loops run faster than one loop that does multiple things?

texts:
My game had some lag, so I tried to improve the performance.

I found that if I write my loops separately like this:

for (...){
    for (...){
        // Do operation A
        // (Fill int[][] with 1s)
    }
}

for (...){
    for (...){
        // Do operation B
        // (Work with Sprite Renderers & Spritebatch)
    }
}

for (...){
    for (...){
        // Do operation C
        // (Work with Shape Renderers with alpha)
    }
}

then the result runs a whole lot faster than if I try to do all the operations in one loop:

for (...){
    for (...){
        // Do operation A
        // Do operation B
        // Do operation C
    }
}

Can anyone explain this?

I'm running this game on Android OS!


texts: Why I need a backend for a mobile social game?

texts:
I'm developing a mobile social game, it's a puzzle with a social layer similar to the one in Candy Crush Saga (limited lives, can send life requests to friends, facebook leaderboards, etc). I know all top mobile social games have a backend, but I don't understand what's the purpose of it, is it only to persist game data? Assuming I'm not interested in persist game data online, do I need a backend server?

My idea was to handle all players' interactions through facebook (life request, leaderboards, etc). Is this possible without my own backend?

Any information on what are the benefits of having a backend for a mobile game is welcome.


texts: How do I correctly implement Java animations?

texts:
Here's what I have so far.

//Inside the Animations class
public void update() {
    timer +=System.currentTimeMillis() - lastTime;
    lastTime = System.currentTimeMillis();

    if(timer>speed) {
        Playing=true;
        index++;

        timer=0;
        if(index>=frames.length) {
            index = 0;
            Playing=false;
        }
    }

}//Getters and setters down

In the main state

    @Override
public void update() {
    Ability.update();
        if(AttackP.isPlaying()) {
            AttackP.update();

        }

    //gets
    HealthCheck();
    getMousePosition();
}

...

    if(turn==true) {//Only run when it's the players turn
        if(MousePressed&&!AttackP.isPlaying()&&!AttackingP) {
//if left clicked when animations are not playing and when AttackingP is false
            buttonCheck(g);//next
        }else if(!MousePressed) {//set Attacking to false when mouse not pressed
            AttackingP=false;
        }

...

private void buttonCheck(Graphics g) {
    if(MouseX<501&&MouseX>420&&MouseY<531&&MouseY>500){//if the mouse is in this button

        AttackingP=true;
        StartAnimation(g);

        }

...

    private void StartAnimation(Graphics g) {

    g.drawImage(getCurrentAnimationFrame(),175,0,512/2,512/2, null);//play animation
    BossHealth-=5;
    turn=false;

}

public BufferedImage getCurrentAnimationFrame(){
    return AttackP.getCurrentFrame();
    }

The problem is, when I press the button, the animation only renders 1 frame, not the others in the BufferedImage array.

Help appreciated, I've been stuck on this part for 2 days now.


texts: Transparent textures being handled oddly

texts:
In OpenGL why is it that when rendering transparent textures it changes the color values of all the pixels? Ex. when this transparent texture is rendered it comes out as this. Also if I change the texture to not have transparency it still has the same problem of changing pixel values. What causes OpenGL to completely change a transparent texture when it is rendered? (Note: the textures have been created in GIMP and the program is running on a mac (OSX 10.10.3))

EDIT:

Turns out this happens when you load a texture with transparency on the RGB color spectrum instead of the RGBA spectrum.


texts: what file architecture to follow while uploading an sdl based C++ project to Github?

texts:
I created this sdl game containing header files source files and graphics files including tilemaps .
I also have a setup file that will install a .exe file with dependencies such as dll files for sdl .
Which files and in which architecture should I upload this project to Github?


texts:
I want to include some locked levels in my puzzle app as a lightweight reward system. The levels play relatively quickly (average 1-min/level) and there are 100-200 levels in a pack. I prefer not to enforce a strict sequential ordering of play (I'm worried that a "wall" of 200 locked levels looks somewhat daunting and does not allow any exploration).

I propose (for example) that the player must solve puzzles #1-4 (in any order) to unlock #5, #6-8 (in any order) to unlock #9, #10-13 to unlock #14, and so forth. The locked levels have no dependencies other than you must solve those puzzles immediately preceding it and after the last locked level (e.g. you can unlock level #9 without unlocking level #5).

While I don't expect to convey all the subtleties/rules of unlocking, would the following graphic be "good game design" practice for showing the locked levels? Would one reasonably assume they had to solve #1-4 to unlock #5? (I know that this a subjective question, but game design psychology can be a pretty subjective topic).


texts: Is it possible to read the frame to be output to the screen from GPU in XNA?

texts:
I want my XNA game to do its thing and at the end of the Draw() call read the the frame that is sent to the screen into memory (which in XNA would presumably be a Microsoft.Xna.Framework.Color[]).

Is is possible to this from XNA? If so how and when should I do it? Immediately before or after my:

base.Draw(gameTime);

call?


texts: Should I use OpenGL while working with C++?

texts:
I am completely new to programming and game development for that matter. I am using the C++ software to create my Game Engine with the help of a beginners guide. I noticed it has a OpenGL option when starting up a new project. I've heard of OpenGL pertaining to game development, not sure what it is though.

Should I be using OpenGL when creating my Game Engine? Will it matter if I just start with a blank slate?


texts: Can UE4 be used from multiple locations with a single license?

texts: I want to subscribe to Unreal Engine 4 with my small game development team. But before we do, we have a question: can we also use UE4 from multiple locations at the same time? So that all of our developers have access to UE4 with just the fee of $19/month?


texts: As an indie game developer, how can I have (quality) music/sound done?

texts:
Besides the story itself, a game needs code, graphics and music/sound effect. I can program and I knew a few graphics designers in the web app era. However, I don't know whether to find music and sound freelancers/professionals/partners.

So how's music/sound typically done? Do you finish a game and hand it to some musicians? Seek help via Facebook? Call the secondary school music teacher? .. Please advise. Thanks!

EDIT:

I'd like to rephrase the question a bit to clarify the objective. Let's start with example. Say, there is designer which have finish a great UI concept design, and ask: "how can I find programmers to transform this design into an app?"

It won't help him much by telling where github is and how much great codes can be learned from... He needs the judgement of what are good code, in addition to how to use the code, and most importantly, the ability to modify/enhance the code to fit his need.

As a programmer, all I know a game needs some good music. The question is not about where to find music. The question is how to find musician who knows music, the music which fits my game. It's similar to the design is looking for a programmer who can turn Photoshop into .app rather and programming books and code samples.

Simply put, where did you find your game's musician? ;-)

p.s. I found my graphics designer on deviantart.com Where is the deviant music.com? XD


texts:
I am implementing Unity Ads in my game and for some reason I have the test ads showing up in my production version of my app. I have the advertisements initialized with test ads turned off and I have even gone into my settings on the Unity Ads admin and set it to force test ads to be off. I'm not sure what else to do here.

Here is how I am initializing:

Advertisement.Initialize("myID", false);


texts: Generating circular bounding volume / AABB for bone animated object

texts:
I have the animated bounding boxes for the individual bones of an object which comes from a pre-computation of the bone's bounding boxes multiplied with the bone matrix. In this question I'm referring to the surrounding aka overall BB for the model. I get it by looping through the precomputed bounding boxes of the bones.

I'm able to get an OBB but not an AABB or circular volume because I can't get into the correct "space" for the center of the volume. I thought that getting an AABB would be very easy, but since I have the min/max points in bone space (?) I need to do some operation to disable rotation. All I can get is OBB :(

I figure that the aabbV4 vector is in "bone space". So, I have to take the inverse of that space somehow, but since I have the combined value of each bone, I need the AABB / circular volumes to follow tutorials on collision detection and not just OBB that I have now.

So, each object has multiple bones which have a bounding box which animate each frame according to a bone matrix. Then, the mvpGet() function creates the MVP matrix which moves / rotates / scales the whole thing.

I render the OBB / surrounding volume of the bones like this:

for (auto &i : myAbj.allObj)
{
    if (i->bb->val_b && i->anim->val_b)
    {
        i->aabbV4.clear();

        for (auto &j : i->bbSkelAll)
        {
            for (auto &k : i->aiGbones)
            {
                if (k.name == j.name)
                {
                    i->obbMVP = glm::transpose(k.animatedXform) * j.obbMVP; // precomputed obbMVP

                    //AABB - STEP 1 - GATHER / STORE
                    glm::vec4 bbSkelXformMin = glm::transpose(k.animatedXform) * glm::vec4(j.min, 1.f);
                    glm::vec4 bbSkelXformMax = glm::transpose(k.animatedXform) * glm::vec4(j.max, 1.f);
                    i->aabbV4.push_back(bbSkelXformMin);
                    i->aabbV4.push_back(bbSkelXformMax);

                    break;
                }
            }

            i->mvpGet();
            i->render();
        }
    }
}

 //AABB - STEP 2 - MIN / MAX
for (auto &i : myAbj.allObj)
{
    if (i->bb->val_b && i->anim->val_b)
    {
        glm::vec4 aabbMin = (i->aabbV4.empty()) ? glm::vec4(0.f) : i->aabbV4[0];
        glm::vec4 aabbMax = (i->aabbV4.empty()) ? glm::vec4(0.f) : i->aabbV4[0];

        for (uint j = 0; j < i->aabbV4.size(); ++j)
        {
            aabbMin = glm::min(i->aabbV4[j], aabbMin);
            aabbMax = glm::max(i->aabbV4[j], aabbMax);
        }

        glm::vec3 aabbSize = aabbMax - aabbMin;
        glm::vec3 aabbCenter = .5f * (aabbMin + aabbMax);
        i->aabbMVP = glm::translate(glm::mat4(), aabbCenter) * glm::scale(glm::mat4(), aabbSize);

        i->aabbTgl = 1;
        i->mvpGet();
        i->render();
        i->aabbTgl = 0;

        cout << "aabbCenter = " << glm::to_string(aabbCenter) << endl;
    }
}


texts:
I have a simple object created from PLANE, in BLENDER version 2.72, where I edged the edges to the height. How do I correctly export the model to Unity3d I have version 4.7 to make all walls visible? Figure 2. Sorry for the wrong English. Thanks for your advice

Picture 1 in Blender

object export .obj in unity


texts: How could we use trigonometry for moving around a 3D World?

texts:
Well I have a question about geometry and 3-Dimensional player movement in general. I'm using Java, OpenGL and LWJGL.

This is basically what I got:

currentFrontSpeed: Is a float that contains the speed of the Player.
player. increasePosition: Just adds the current Position of the Player to the value that is given on the X, Y and Z axis.

//The point we want to go: Forwards(+) Backwards(-). getFrameTimeSeconds
//just adjust the speed depending of the speed of the computer.

float distanceFront = currentFrontSpeed * DisplayManager.getFrameTimeSeconds();

//Distance of Movement
float fx = (float) (distanceFront * Math.sin(Math.toRadians(player.getRotY())));
float fz = (float) (distanceFront * Math.cos(Math.toRadians(player.getRotY())));

//This just increase the position of the player (x,y,z)
player.increasePosition(fx, 0, fz);

Another thing that I didn't explained is that the Player is always looking at the same position as the camera (if the camera turns to the right, the player would also turn to the right. Like Maincraft). That's why I use the Y-Axis to move.

The problem is that my player can only move forwards and backwards (if currentFrontSpeed is positive, my player will move FORWARDS, and if is negative BACKWARDS). And the only form to go to a place that is to the right is to move the Camera to the right and the press UP to go FORWARDS.

I've tried to achieve this doing this:

   //The same as above, the speed of the player this time Right(+) and Left(-)
    float distanceSides = currentSideSpeed * DisplayManager.getFrameTimeSeconds();

    float sx = (float) (distanceSides * Math.cos(Math.toRadians(player.getRotY())));
    float sz = (float) (distanceSides * Math.sin(Math.toRadians(player.getRotY())));

    //I just add the "horizontal" speed to the "vertical" one
    player.increasePosition(fx + sx, 0, fz + sz);

Of course this doesn't work good: if the player Y-rotation is 0, the player moves to the right and to the left perfectly; but for example, if the player rotation is 90 (looking at the right from the original position), moving up or moving to the right would take us to the same position (because is the "right" from the original position with the Y-axis 0).

I don't know if I should use another trigonometric function or add the sx and the sz to another value in the X, Y and Z axis.

EDITED

I've just edited and gived some information because of the bad explaining I did. Also this is one of my first long-writed post.

Thanks for helping!


texts:
I know this has been asked before, but I don't understand why my code isn't working.

I'm doing top-down collision with no gravity.

Here is my code :

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

public class TankBodyControls : MonoBehaviour {

public KeyCode Foward = KeyCode.W;
public KeyCode Backward = KeyCode.S;
public KeyCode TurnLeft = KeyCode.A;
public KeyCode TurnRight = KeyCode.D;

public const float MaxSpeed = 6.0f;
public const float RotSpeed = 4.0f;

private Rigidbody2D TankBody;

void Start () {
    TankBody = GetComponent<Rigidbody2D>();
}

void OnCollisionEnter2D(Collision2D coll)
{
    print("called");
    if(coll.collider.CompareTag("wall"))
    {
        print("collided!");
        var P = transform.position;
        P.x -= TankBody.velocity.x;
        P.y -= TankBody.velocity.y;

        transform.Translate(P);
    }
}

private void MoveTank()
{
    var Vel = TankBody.velocity;

    if(Input.GetKey(Foward)||Input.GetKey(Backward))
    {
        float VelMag = (Input.GetKey(Foward) ? MaxSpeed : -1.0f * MaxSpeed/2.0f);
        float VelAngle = transform.eulerAngles.z * ((float)Math.PI / 180f);
        Vel = new Vector2((float)Math.Cos(VelAngle), (float)Math.Sin(VelAngle));
        Vel *= VelMag;

        var rot = TankBody.rotation;

        if (Input.GetKey(TurnRight))
        {
            rot -= RotSpeed;
        }

        if(Input.GetKey(TurnLeft))
        {
            rot += RotSpeed;
        }

        TankBody.rotation = rot;
    }
    else
    {
        Vel = Vector2.zero;
    }

    TankBody.velocity = Vel;
}

void Update ()
{
    MoveTank();
}
}

The idea was : if I detect a collision, shift the player out of the wall, the distance (velocity) they intersected it. My problem right now is, the OnCollisionEnter2D function doesn't even get called when they intersect (hence not console prints). Any idea what I'm doing incorrectly?


texts: The state that is synced when a window is broken in a FPS game

texts:
In order to better understand how state syncing works in games, I wanted to pose a specific example. Say you are in a FPS game with multiple players and someone breaks a window in some building. Wondering what happens in terms of state syncing. For example, there are these aspects:

Someone else is watching the player break the window in the game. So it should probably be a real-time update.
Someone isn't watching but they hear the sound of the window breaking.
Someone is out of range of hearing or seeing the window break, so wondering if it still updates their game world, or it somehow lazily picks up the changes when they go to the area with the broken window.

Wondering how it generally works in these different scenarios. Any FPS game is fine. For example, in (1), if they are sending each individual particle of broken glass over the internet, or somehow they just send the generic action "user x threw object y at window z" and it replays the action on everyone's computer who is watching. In which case somehow the game world is broken up into macro chunks rather than being composed of particles. In (2), maybe they divide the level into zones of seeing and hearing range, and somehow send just the right amount of state then (wondering what kind of state, and how much). Then in (3), if it is lazily picked up, then what sort of queue is kept on the backend. If the data is compressed when it is sent, etc.


texts:
So I'm working on one thing that I can't figure it out at this moment. Lets say that I have my all game data compressed into zip archive. There's a scripting system in the game that lets you to do some stuff. For example spawn npcs, equip specific items, etc.

Where's the problem? When I'm loading my world that is separated into chunks it's quite easy to load needed assets and other data without any notice. But lets say I write a script that triggers an explosion after a button press. In that moment game needs to load explosion textures, etc. Without separate threads, on slower system, the game would definitely freeze for some time. If I would use separate threads after all - on the slower system it may cause missing textures problem or something like that.

So it's quite easy to load up ahead some resources while loading world chunks, but how to foresee what resources should be loaded for objects that will be seen after script execution?

I don't know if it's possible to understand what I want to do, but I can give another example. In Bethesda's games like Fallout 3 or TES you can use spawn command that shows up constructed npc with all the textures right away. Any ideas how they load up textures and models so quick?


texts: c# Unity - Matrix output incorrect on vector rotation

texts:
I have a input Vector (1,1,0) when I run it through a  Unity Matrix4x4 class with a rotation of 90 degrees around the Z axis the output is (-0.9999999,1,0) which is nearly correct but strange. But (2,0,0) with the same degrees and axis rotation I get (1.192093e-07,2,0). The Y vector coordinate is correct, but why on earth is X set to 1.192093e-07? I cant explain why this is happening. I thought it would be set to (0,2,0).

The code I am using

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour
{
public Vector3 translation;
public Quaternion rotation;
//public Vector3 eulerAngles;
public Vector3 input;
public Vector3 output;
public Matrix4x4 m;
// Use this for initialization
void Start ()
{
    //transform.rotation = Quaternion.Euler(60F, 0, 45F);
}

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

    input = new Vector3 (2, 0, 0);
    rotation = Quaternion.AngleAxis(90, Vector3.forward);
    m = Matrix4x4.TRS (Vector3.zero, rotation, Vector3.one);
    output = m.MultiplyPoint3x4(input);

    }
}

You can see Vector forward is the Z axis. I have scale as (1,1,1) and no transformation set. I have Unity set to 2D view. I have a main  camera with a Orthographic view, clipping plane near is 0 and far is 1000 and its depth is -1, its vector is (0,0,0).

When I use (2,0,0) as the input this is the result of the matrix

[E00] = 5.960464e-08 [E01]  = -0.9999999 [E02] = 0 [E03]  = 0
[E10] = 0.9999999 [E11]  = 5.960464e-08 [E12] = 0 [E13]  = 0
[E20] = 0 [E21]  = 0 [E22] = 1 [E23]  = 0
[E30] = 0 [E31]  = 0[E32] = 0 [E33]  = 1


texts:
I am pretty new to Monogame, and I'm trying to draw a character sprite and move it using keyboard. Instead of moving to different positions, it leaves a track of copies along the way.

I have 2 game states; one is the menu, and the other one is the level, where the sprite is called to draw.

Why is my sprite leaving copies as it moves in Monogame?

Player.cs

class Player : Entity
{
    private float velocity;
    private int hp;
    public Texture2D texture;
    public Rectangle hitbox;
    public Vector2 pos;
    KeyboardState oldState;

    public void Init(ContentManager content)
    {
        texture = content.Load<Texture2D>("char");
        hitbox.Width = texture.Width;
        hitbox.Height = texture.Height;
        velocity = 150f;
        pos.X = 100;
        pos.Y = 100;
    }

    public void Update(float delta)
    {
        KeyboardState newState = Keyboard.GetState();

        if (newState.IsKeyDown(Keys.D))
            pos.X += 100 * delta;
        if (newState.IsKeyDown(Keys.A))
            pos.X -= 100 * delta;

        oldState = newState;
    }

    public void Draw(SpriteBatch sb)
    {
        sb.Begin();
        sb.Draw(texture, pos, Color.White);
        sb.End();
    }
}

Level1.cs

class Level1 : State
{
    private Texture2D background;
    public Player player;

    public void Init(ContentManager content)
    {
        //background = content.Load<Texture2D>("Level1/bg");
        player = new Player();
        player.Init(content);
    }

    public void Update(float delta)
    {
        player.Update(delta);
    }

    public void Draw(SpriteBatch sb, GraphicsDeviceManager graphics)
    {
        player.Draw(sb);
    }
}

Game1.cs

public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    State CurrentState;
    KeyboardState oldState;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    void SetState(State state)
    {
        GraphicsDevice.Clear(Color.White);
        CurrentState = state;
        CurrentState.Init(Content);
    }

    protected override void Initialize()
    {
        SetState(new MenuState());
        graphics.PreferredBackBufferWidth = 1920;
        graphics.PreferredBackBufferHeight = 1080;
        graphics.IsFullScreen = true;
        graphics.ApplyChanges();
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void Update(GameTime gameTime)
    {
        KeyboardState newState = Keyboard.GetState();

        var delta = (float)gameTime.ElapsedGameTime.TotalSeconds;

        CurrentState.Update(delta);

        if (CurrentState is MenuState && (newState.IsKeyDown(Keys.F)
            && oldState.IsKeyUp(Keys.F)))
        {
            SetState(new Level1());
        }

        if (CurrentState is MenuState && (newState.IsKeyDown(Keys.Escape)
            && oldState.IsKeyUp(Keys.Escape)))
        {
            this.Exit();
        }

        if (CurrentState is Level1 && (newState.IsKeyDown(Keys.Escape)
            && oldState.IsKeyUp(Keys.Escape)))
        {
            this.Exit();
        }

        base.Update(gameTime);
        oldState = newState;
    }

    protected override void Draw(GameTime gameTime)
    {
        CurrentState.Draw(spriteBatch, graphics);
    }
}


texts: Unity 2d: How stop movement when object hit a wall

texts:
I created a square that slides on a flat ground.

public class PlayerMoveScript : MonoBehaviour
{

float move = 0;

    void Start (){}

    void FixedUpdate ()
    {
        if (move == 0) {
            move = Input.GetAxis ("Horizontal");
            if (move != 0) {
                move = 15*Mathf.Sign(move);
                rigidbody2D.velocity += new Vector2 (move, rigidbody2D.velocity.y);
            }
        } else
            {
            rigidbody2D.velocity = new Vector2 (move, rigidbody2D.velocity.y);
            }

    }
}

On both sides of the ground lies a wall, when the square hits a wall and stops his movement, the square instead continues to push in his direction.
What I trying to do, is that when the square hits the wall, the square stop the movement and stop to push on the wall, in a way that the player can choose a new direction until the square will hit a new wall.

So imagine a big picture frame, a little square lies on the center.

The player hit the down key
The square starts to move down, with a constant velocity
The square hits the bottom side of the frame, and it stops
The player choose a new direction.
The square starts to move in the new direction
Back to 2

N.B: The walls are rigid bodies 2d with a box collider 2d.


texts: uniform matrix not being assigned to shader

texts:
im trying to apply a rotation matrix to my shader and when i try to set it and mult it in the shader my triangle doesn't render

my drawing code:

        var rotmat = Matrix4d.CreateRotationZ(45);

        shader.SetMatrix("transform", rotmat);

        shader.Use();
        mesh.Draw();

shader.SetMatrix:

    public void SetMatrix(string name,Matrix4d mat)
    {
        int index = GL.GetUniformLocation(Program, name);
        GL.UniformMatrix4(index, false,ref mat);
    }

vertex shader code:

#version 440 core
layout (location = 0) in vec3 position;
layout(location = 1) in vec4 color;
layout(location = 20)uniform mat4 transform;

out vec4 fragcolor;

void main(void)
{
  gl_Position = transform * vec4(position,1.0);
  fragcolor = color;
}


texts: What's an optimal procedure to create a connected cyclic grid of nodes and edges for A* pathfinding

texts:
like the title says, I'm trying to create a grid of nodes that hold edges or connections to each other so I can perform A* algorithm to have objects traverse across them as seen in your standard RTS.

I want to know if there is a general structure and algorithm for this node grid data structure as I can't find a good resource online. For instance, I will be moving my objects via position (Vector3) so I will have to calculate my edge weight to be the magnitude between two nodes. Is this a standard practice?

Could anyone perhaps guide me to the rough basics on how this is achieved in a standard RTS? I would greatly appreciate any information!


texts: Is it legal to publish a Noughts and crosses (tic-tac-toe) game?

texts: Is it be legal to publish a Noughts and crosses game?