texts: Android OpenGL ES 2 framebuffer not working properly

texts:
I'm trying to understand how framebuffers work. In order to achieve that, I want to draw a very basic triangle to a framebuffer texture and then draw the resulting texture to a quad on the default framebuffer.

However, I only get a fraction of the triangle like below. LE: The triangle's coordinates should be (1) -0.5f, -0.5f, 0 (2) 0.5f, -0.5f, 0 (3) 0, 0.5f, 0

Here's the code to render:

@Override
public void onDrawFrame(GL10 gl) {
    renderNormalStuff();
    renderFramebufferTexture();
}

protected void renderNormalStuff() {
    GLES20.glViewport(0, 0, texWidth, texHeight);
    GLUtils.updateProjectionMatrix(mProjectionMatrix, texWidth, texHeight);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fbo[0]);

    GLES20.glUseProgram(mProgram);

    GLES20.glClearColor(.5f, .5f, .5f, 1);
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

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

    GLES20.glUniformMatrix4fv(u_MVPMatrix, 1, false, mMVPMatrix, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vbo[0]);
    GLES20.glVertexAttribPointer(a_Position, 3, GLES20.GL_FLOAT, false, 12, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vbo[1]);
    GLES20.glVertexAttribPointer(a_Color, 4, GLES20.GL_FLOAT, false, 16, 0);

    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, ibo[0]);
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, indexBuffer.capacity(), GLES20.GL_UNSIGNED_BYTE, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);

    GLES20.glUseProgram(0);
}

private void renderFramebufferTexture() {
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);

    GLES20.glUseProgram(fboProgram);

    GLES20.glClearColor(.0f, .5f, .25f, 1);
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    GLES20.glViewport(0, 0, width, height);

    GLUtils.updateProjectionMatrix(mProjectionMatrix, width, height);

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

    GLES20.glUniformMatrix4fv(fbo_u_MVPMatrix, 1, false, mMVPMatrix, 0);

    //draw the texture
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
    GLES20.glUniform1i(fbo_u_Texture, 0);

    GLUtils.sendBufferData(fbo_a_Position, 3, quadPositionBuffer);
    GLUtils.sendBufferData(fbo_a_TexCoordinate, 2, quadTexCoordinate);

    GLES20.glDrawElements(GLES20.GL_TRIANGLES, quadIndexBuffer.capacity(), GLES20.GL_UNSIGNED_BYTE, quadIndexBuffer);

    GLES20.glUseProgram(0);
}


texts: Is there a way how to handle multiple SDL_PollEvent loops without clearing the event queue?

texts:
Is there a way how can I handle more SDL_PollEvent while loops for one SDL Event, without taking the events off from the event queue?

Let us say I have something like this:

void Game::processInput() {

    SDL_Event event;
    SDL_PollEvent(&e);

    Engine::InputManager::processInput(&e)

    GUI_Library::InputManager::processInput(&e);
}

And then the engine processes the input in function like this:

    void Engine::InputManager::processInput(SDL_Event* e) {

    _mainEvent = *e;

    while (SDL_PollEvent(&_mainEvent)) {

        switch (_mainEvent.type) {

            case SDL_KEYDOWN : {

                Engine::InputManager::pressKey(_mainEvent.key.keysym.sym);
                break;
            }
            case SDL_KEYUP : {

                Engine::InputManager::releaseKey(_mainEvent.key.keysym.sym);
                break;
            }
        }
    }
}

However, this while loop clears the whole event queue, and another input manager (my GUI, for example) does nothing because it no longer has events in the queue.

Is there a possible way to handle this situation?


texts: Steer a flock towards a target? Like in pikmin?

texts:
Can a flock be steered towards a target ?

I've seen that flocking behavior has the alignement behavior, but can it be directed and steered toward a goal ?

http://www.youtube.com/watch?feature=player_detailpage&v=BKJyv4uqsWI#t=305


texts: Tile based movement with SKAction (Xcode 8, Tile Map)

texts:
I am trying to make a game where the Hero can move like in Pokemon with SKActions.
But the movement looks unprofessional and have delays.
How can we handle to move the Hero smoothly with SKActions from tile to tile without checking every frame if up is touched?

(the Joystick sends just a signal if a direction is pressed and released)

Edit: I am using Xcode 8 and the new Tile Map function


texts: How do I set up my modifier system without casting?

texts:
I am trying to create a system that can easily modify objects on the fly. For example, lets say I have an Entity2D that inherits from Entity. Entity2D has a Position property. I also have a class called ModifyPosition that inherits from Modifier.

Here is the code:

public class Entity
{
    /// Applies the modifier to this entity.
    /// <param name="modifier">The modifier to apply.</param>
    public void ApplyModifier(Modifier modifier)
    {
        modifier.Apply(this);
    }
}

/// Modifies an entities position
public class ModifyPosition : Modifier
{
    /// /// Initializes a new instance of the <see cref="ChangePosition"/>
    class.///
    /// <param name="position">The position.</param>
    public ChangePosition(Vector2 position)
    {
        this.Position = position;
        this.IsModifyingChildren = false;
    }

    /// Gets the position.
    /// <value>The position.</value>
    public Vector2 Position { get; private set; }

    /// Applies this change to the specified entity.
    /// <param name="entity">The entity.</param>
    internal override void Apply(Entity entity)
    {
        ((Entity2D)entity).X += this.Position.X;
        ((Entity2D)entity).Y += this.Position.Y;
    }
}

If you are calling this multiple times per second, I would think that the casting would slow it down. Is there another way to go about this, without having to cast?


texts:
I'm currently undertaking a personal project at home that I need to turn around inside the next few months (which working full time and still learning programming makes it a tad difficult). I'm looking for suggestions on SDK's or tools (preferably free or that come with games, similar to steam tools) that I can use to develop a "game". I'm OK with coding but have no 3D development skills at all.

I've very little experience with mod tools or SDK's at all but I'm hoping someone can point me in the direction of one that does the following:

A decent library of prefab 3D models to build scenes.
Ability to add scripting to the scene

I've used Unity before and would prefer to continue to do so however I really have the worst 3D skills imaginable and can't waste time learning them.

I'd be looking for pre-fab items that are both industrial and possibly more lush environments (trees etc). If it makes any difference (due to licencing and what-not) I WILL NOT be selling this game or marketing it in any way and I am a University Student if any places do educations licences.

Another alternative would be to source free 3d models elsewhere but again while I'm still learning I have no idea where to look if someone could point me in the right direction I'll do the rest of the digging.

Thanks


texts:
I am trying to spawn some entities on a navmesh at runtime. The entities need to spawn at a random point.

Right now i use the following to get a random point:

public Vector3 GetRandomPointOnMesh()
{
    Vector3 randomDirection = UnityEngine.Random.insideUnitSphere * maxDistance;
    randomDirection += transform.position;
    NavMeshHit hit;
    NavMesh.SamplePosition(randomDirection, out hit, maxDistance, 1);

    if (float.IsInfinity(hit.position.x) || float.IsInfinity(hit.position.y) || float.IsInfinity(hit.position.z))
        return GetRandomPointOnMesh();

    return hit.position;
}

My problem here is, some time that random point inside the sphere is not hitting the navmesh, hence the recursive call until it actually hits the navmesh.

How can i make this piece of code run in the background until there is an actual value returned. Cause this holds up the main thread till a value is obtained.


texts: Box2d How to connect distance joint to the ground?

texts: I have a rectangular fixed size world. I want to connect a body inside it to any place(near that body) in the world with a b2DistanceJoint. Do I need to create a large static body with the size of the world that can't collide with anything? Or is there a better method? Will it slow down simulation speed if I have around 300 bodies moving on the surface of this static body?


texts: Which approach to use when simulating a button press in a cockpit?

texts:
As the picture shows, I wish to press a button when I am flying the plane.
I'm writing the program in DirectX 12 and C++, without a game engine.
I am new to this, so I don't know which approach to use to simulate the button press. Should I use a skeleton and make an animation binding to the bone, or just program the button position in code?


texts: how can i create a snake with a single piece look

texts: I want to create a 3d snake with a single piece look, i have tried separate head and body parts following each other with Vector3.SmoothDamp but some quaternion issues occurred (when y axis >90, pieces turning upside). What I want is exactly like in the video https://youtu.be/uWlMvHU2wfQ Could you tell me the unity components I need to know/research? Are the snake models in the video rigged?


texts:
I have a problem which I don't really know what to call, and I would like to apologize in advance for perhaps the misleading title. Let's say I break a few objects in the 2D game and they scatter along the floor, I want the objects to now become apart of the floor.

The solution doesn't have to account for movement, it can wait till the object has come to a stop before updating the terrain. It is intended the terrain doesn't produce any concave shapes as I assume that would just add a whole new layer of complexity.

I thought of a few solutions but I am completely new to this all and if all you can do is point me in the right direction I would greatly appreciate it.
What am I actually asking? I am honestly just looking either for the general Maths involved, or what this type of process is even called if it has a proper term or a few suggestions for a solution.

(In the images, the blue rectangles are rigid bodies, the black lines are the edges of the environment, and the red line is the floor/terrain that changes in relation to the blue rectangles)


texts: Affect movieclip scale from a .as doc to another

texts:
I've been working on a game following a tutorial on the internet, the game is an avoider where you have the Avatar, that has to avoid the objects that fall.

The way it is made is: I have a DocumentClass which addChild's the screen you should be seeing and removeChild's the screen that you were.

For example: first it loads the menuScreen, then when you press play unloads menu and loads playscreen. When you die it loads the gameoverScreen and loads the playscreen.

And from the gameOverScreen you can press the SHOP button to go to the shop.
From here on I'm on my own and not following any tutorials.

The shop has a button that is supposed to alter the Avatar's X and Y scale to 0.5, but the problem is: how do I make that work?

I tried creating a sharedObject.data.avatarSize, on the store's size button the code would be something like:

sharedObject.data.avatarSize *= 0.5;

And on the AvoiderGame.as, which is the most of the actual game, on the part where the avatar is created I tried putting this after it's creation:

scaleX.avatar = sharedObject.data.avatarSize;
scaleY.avatar = sharedObject.data.avatarSize;

This did not work since it gives me the error 1009 saying can't access something that is null. I tried this before "using" the sharedObject:

if( sharedObject.data.avatarSize == null )
{
    sharedObject.data.avatarSize = 1;
}

But it did not work...

So now I'm not sure on what to do. I know we should reduce global variables as much as we can but how do I do it?

--EDIT--

Also, if it helps, I'm using Flash CS5 and working with AS3.0 and if you don't know about flash, you can also tell me how you would do it on any other language and I would try to convert it to flash.


texts: How do multiple shaders in a DirectX Engine work?

texts:
So as I have been learning DirectX 11, I have been looking at a few tutorials online and in the sample code provided there are more than the usual pixel and vertex shaders (along with the geometry shaders etc..). Based on my understanding there should be minimum 2 shaders (vertex & pixel) which work together.

With these additional shaders how do they work with the vertex and pixel shaders? In these additional shaders there are alse PS and VS functions so could someone explain whats going on here? So as soon as I call the return function in one shader the data is passed to the next?


texts: Why aren't my isometric objects where I think they are?

texts:
Background
I am creating an isometric RPG using Tiled and Monogame. My goal is to have relatively elaborate terrain and movement, with my vision for the overworld being much like the now-venerable Megaman Battle Network franchise. As such, by world must be 3D and simply drawn on top of an isometric map assembled from tiles.
Quirks
The Monogame.Extended system for drawing Tiled maps does so mostly on its own, though I have elected to draw a layer at a time and render any sprites I need to between the layer draw calls. The layers do not use the SpriteBatch I have configured to draw movable sprites, and just take a translation. I've managed to become decently adept at navigating it to convenient locations.
The Issue
Wikipedia says that for a good isometric scene, you want to rotate 45 degrees around Z and something like 32 degrees around what in my system is X. In my case, the resulting transformation does not seem to match the map image, so I am using an angle of approximately 52 degrees around X, which matches up fairly well. However, while the map itself can be perfectly aligned to the collision system, and I'm able to walk around the edges perfectly, objects within the map seem oddly placed. Some of this may be due to my incorrect handling of the Z (world upward) index, but it seems more than that. When I align the image so that it lines up with them instead of the edges of the map, their sizes seem subtly incorrect - I have found, for instance, that if my X rotation is negative, the objects (which are distant) seem slightly smaller than how they are drawn. I could be misreading that, however.
EDIT: The only distortion, if there is indeed any, seems to be in the viewport's Y direction. I collide where I expect to horizontally.
My Assumption
I believe this may simply be a camera issue - perhaps the default camera is not orthographic or something?  I don't really know the way to fix that if so, and if not, I'm mystified by what is going on.


texts: How to implement a restart button after game over?

texts:
How would one go about implementing a method in which it calls the game to restart by pressing a button after game over?

I have my game class which puts the player in and starts the enemy sequence shown below. I already have my restart button as shown in the code snippet from the mouseinput class below and the problem is I don't know what to put in the area where the question marks are to get the thread to restart, if I'm using the appropriate language or not I'm not sure. I'm new please bare with me.

Thank you. What I'm doing now isn't working because it's glitching and the fps is shaky.

public Game()
{
    new Window(1000, 635, "Galaxy Monkeys", this);
    start();

    handler = new Handler();
    camera = new Camera(0, 0);
    this.addKeyListener(new KeyInput(handler));
    menu = new Menu(this);

    BufferedImageLoader loader = new BufferedImageLoader();
    sprite_sheet = loader.loadImage("/spritesheet.png");

    Enemy enemy = new Enemy(-20, r.nextInt(563), ID.Enemy, handler, this);
    Monkey p = new Monkey(500, 250, ID.Player, handler, this);

    handler.addObject(p);

    for(int i = 0; i < enemy_count; i++)
    {
        handler.addObject(enemy);
    }

    this.addMouseListener(new MouseInput(handler, camera, this));
    background = loader.loadImage(("/background.jpg"));

    INSTANCE = this;
}

Restart event on MouseInput.java:

public void mousePressed(MouseEvent e)
{
    int mx = (int) e.getX();
    int my = (int) e.getY();

    if(Game.state == STATE.GAMEOVER)
    {
        if(GameOver.restartButton.contains(mx, my))
        {
            // Pressed Restart Button
           Game.setState(Game.STATE.GAME);
            Game.INSTANCE = new Game();
        }
    }
}


texts: RogueLike - Map and Entities - how to store it?

texts:
Started to write my own RL, and already fell into analysis (paralysis?) when implementing map class.

My TILE class looks like:

class CMapTile
{

public:

    enum eMapTileType
    {
        E_UNKNOWN = 0,
        E_FREE,
        E_WALL,
        E_ALL
    };

    CMapTile();
    virtual ~CMapTile();
    uint8_t GetType();
    uint8_t IsBlocking();
    uint8_t GetSymbol();

protected:
    uint8_t m_uiType;
    uint8_t m_uiBlocking;
    uint8_t m_uiSymbol;

};

Then i wrote a class for the map itself

#include "CMapTile.hpp"

class CMap
{
public:

    CMap();
    void Init(const uint8_t& ruiWidth, const uint8_t&  ruiHeight);
    void Generate();
    void Print();
    CMapTile GetTile(const uint8_t& ruiX, const uint8_t& ruiY) const;

private:

    uint8_t m_uiWidth;
    uint8_t m_uiHeight;

    std::vector<CMapTile> m_vTiles;
};

And here is me thinking. With the design above, Map has no idea about entities. Entities have no idea about map.

So when i want to move Player RIGHT given above i will have to make two checks (totally separated). A check for map if tile is blocking and a check in a vector of entities if there is any entity on that position (X+1).

// Obtain tile to the right
CMapTile *pTile = m_Map->GetTile(pPlayer->GetPosX()+1, pPlayer->GetPosY());

// Obtain entity to the right
CEntity *pEntityToRight = m_EntitiesManager.GetEntity(pPlayer->GetPosX()+1, pPlayer->GetPosY());

// Check if blocking
if(pTile != NULL && pTile->IsBlocking() == false)
{

    // Check if any entity there and blocking
    if(pEntityToRight != NULL && pEntityToRight->IsBlocking == false)
    {
        // Update Player Pos to Tile position
        pPlayer->SetPosition(pTile->GetPosX(), pTile->GetPosY());

        // Update Map Entity Id for this Tile
        _Tile->SetEntityId(pPlayer->GetID());
    }
}

Maybe instead i should have an integer in the CMapTile storing an id of an entity, like below:

class CMapTile
{

public:

    enum eMapTileType
    {
        E_UNKNOWN = 0,
        E_FREE,
        E_WALL,
        E_ALL
    };

    CMapTile();
    virtual ~CMapTile();
    uint8_t GetType();
    uint8_t IsBlocking();
    uint8_t GetSymbol();
    int     GetEntityID();
protected:
    uint8_t m_uiType;
    uint8_t m_uiBlocking;
    uint8_t m_uiSymbol;
    int     m_iEntityID; // <<<<<<<-----

};

Thanks to which i can make a simple call to CMap like this to check if i can move player Right:

  // Obtain tile to the right
CMapTile *pTile = m_Map->GetTile(pPlayer->GetPosX()+1, pPlayer->GetPosY());

// Check if blocking
if(pTile->IsBlocking() == false)
{
    // Update Player Pos to Tile position
    pPlayer->SetPosition(pTile->GetPosX(), pTile->GetPosY());

    // Update Map Entity Id for this Tile
    _Tile->SetEntityId(pPlayer->GetID());
}

With the above CMapTile::IsBlocking would have to know about Entity class, to figure out if entity is a blocking type or not.

Questions
This sounds simple but that initial design has an effect on later development. Examples:

What happens later when for an example NPC would have to attack player?

How from the NPC class the logic knows where is the player located or if he (NPC) can move right ? - having no idea about the map.

Should i pass the MAP pointer to the AI logic ?

Which is the proper way to go to separate the logic and make all of the above simple in future stages of development ?


texts:
I want to create a sports simulation game, something along the lines of Championship Manager (if you're not familiar, you can check out https://www.youtube.com/watch?v=t2FlFWP3K28). It's essentially a 2D game with top-down view, with the exception that the ball seems to behave as if it was 3D.

Given that the game is almost entirely 2D and only the ball is 3D, is there a good way to deal with that without making an entirely 3D game just because of the ball? Can the ball be hooked into a 3D physics engine, the rest to a 2D engine and somehow reconcile the two, then when rendering, just make the ball grow the higher it goes and show a shadow, or something along those lines?


texts: How can I get the speed of finger drag using unity TouchPhase.Moved?

texts:
I'm making a mobile game where you control a 3d ball by touch. So far I can get it to roll based on finger down and drag (via TouchPhase.Moved) but I want to be able to detect a fast flick or finger swipe so that I can addforce based on finger speed and let go. Bit like how I would if I was only using TouchPhase.Began and TouchPhase.Ended with calculating start/end position and time duration, but now I think I need to do something in .Moved to keep track of finger speed and get the start and end position of the beginning and end of that fast finger movement. Here's my code so far:
if (Input.touchCount > 0)
      {
          touch = Input.GetTouch(0);

          if (touch.phase == TouchPhase.Began)
          {
              touchdown = true;
          }

          if (touch.phase == TouchPhase.Moved)
          {
              if (touchdown == true)
              {
                  startPos = new Vector2(0, 0);
              }
              else {
                  startPos = Input.GetTouch(0).position;
              }

              touchTimeStart = Time.time;

              direction = startPos - endPos;
              timeInterval = touchTimeFinish - touchTimeStart;

              endPos = Input.GetTouch(0).position;
              touchTimeFinish = Time.time;

              rb.AddForce(direction.x * force, 0, direction.y * force/ moveSpeed);

              touchdown1 = false;

          } if (touch.phase == TouchPhase.Ended)
      {
          startPos = new Vector2(0, 0);
          endPos = new Vector2(0, 0); } }


texts: Random Direction Vector Relative To Current Direction

texts:
I have a 2D vector where the x and y values are randomly generated using a range between -1 and 1 respectively. I use this as the direction to move an object in which works great.

var direction = Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));

What I would like to do is after some period of time, randomly generate a new direction vector, but this time keep the same "relative" direction that it currently has. Probably within 45 degrees or so on either side of the current direction.

So I'd like to randomly generate a new direction vector within a range of 45 degrees on either side of it's current direction vector, and start moving in that new direction. Does that make sense?

I'm not quite sure how to go about this, but I'm sure this isn't too difficult if someone could help get me started. Thanks!


texts:
I know this been asked a millions of time.

First off my Dabbled in a few languages,like Java,C#,Android,Python and unity even though that's not really a language.My Programming is Level as at far below Amateur.

I been conflicted and a bit confused on what to choose.I know there is no Perfect Language.

So here is what i need help with "LONG TERM GOAL"

Web Game/Program
2d Graphics Simple/Pixel
Interactive like a chat room/mmo
Compatible with most Browsers

Now I need help what to really invest months to years into learning.
Do i learn Unity,Flash or something Else.
What do the expert suggest i go with.What ever it is I wanna learn with a full focus.
I am all over the place and its leading me to be a Jack of Nothing.

I Also realize i am not making games for long time i start with hello world and simple chat room or make a simple tic-tac-toe game.I need step 1 rather then then starting at step 234.

Thank you for any Guidance Much Appreciated.


texts: Unity c# bullet randomly changes position

texts:
i have problem in unity im using this code to shoot bullets and it works but when im shooting bullets are moving left automatically or when i will aim it at right it shoots  straight instead i'm using this code right now:

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

public class shootobj : MonoBehaviour {
    public GameObject prefab;

    void Start () {
     prefab = Resources.Load ("projectile") as GameObject;

    }

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            GameObject projectile = Instantiate (prefab) as GameObject;
            projectile.transform.position = transform.position + Camera.main.transform.forward * 2;
            Rigidbody2D rb = projectile.GetComponent<Rigidbody2D> ();
            rb.velocity = Camera.main.transform.forward * 40;
        }
    }
}

what could be causing such thing?


texts: Unity UI Dropdown list rendering on top of other canvases

texts:
I have 2 screenspace canvases in my scene..

Canvas 2 has just the mouse pointer image on it, the canvas has a sort order of 10.

Canvas 1 has everything else on it, it has a sort order of 0.

The mouse pointer renders in front of everything on canvas 1, except for the dropdown list. which is pretty much the standard dropdown from the Create\UI\DropDown menu.

I didnt think it was possible for some things on one canvas to render on top of another, and some things to not.
It obviously is! But how? What is going on? What do I need to change on the dropdown to make it render with the rest of the stuff on its canvas?


texts:
Does anyone know how to set mouselook to always on instead of having to click and hold the RMB?

I would press and hold a different hotkey to "disengage" mouselook and allow object selection. I was just wondering if there is an option to remap the current RMB functionality within UE4, or is it hard-coded into the editor? I'm used to using RMB as walk in a game, and have never made the switch to WASD (this goes back to the days of Doom on PC). Ideally I would like to keep my current movement mapping of RMB-A-S-D where RMB is move forward. I see where I can remap forward from 'W' but remapping it to RMB is not allowed as far as I can tell.


texts:
EDIT: This is for In game Terraforming, kind of like in life is feudal. https://www.google.com/search?q=life+is+feudal+terraforming&rlz=1C1CHBF_enUS792US792&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj73bS6lo7bAhUHzoMKHYlWBhoQ_AUICygC&biw=1920&bih=949

Ediiting pixels vertically makes a line, but horizontally makes a peak the edited terrain pixels are adjacent. The height map resolution is 513.

When I turn on shaded wireframe in scene view, the issue becomes clearer.

When the terrain is tessellated, each vertex/terrain pixel is part of 6 edges. I suppose to fix this issue I would need to double the triangles, having each vertex be part of 8 edges.

What, if any, method could I use to achieve this and rid this behavior?


texts:
I'm using XNA to create an FPS camera that uses a Direction vector instead of a Target vector control the camera's orientation.

I'm having trouble with the math for looking up and down when the camera is rotated about the Y axis. No problems looking left and right.

Here's my code:

Vector3 LookDirection {get;set;}

public void LookLeft(float scale)
{
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationY(MathHelper.ToRadians(scale)));
}

public void LookRight(float scale)
{
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationY(MathHelper.ToRadians(-scale)));
}

public void LookUp(float scale)
{
    //doesn't work when camera is rotated into the X axis
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationZ(MathHelper.ToRadians(scale)));
}

public void LookDown(float scale)
{
    //doesn't work when camera is rotated into the X axis
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationZ(MathHelper.ToRadians(-scale)));
}

I know I need to manipulate both the X and Z components when looking up and down, I just can't figure out exactly what to do. Thanks


texts: How can realistic 3D body-part movement be implemented?

texts:
Say you create a person, monster or robot, with arms, legs, head(s) ... in 3D in a game.

How do you coordinate the body-part movement to achieve the fluidity of real living beings? Is there some theoretical base, or do you just try until it looks good enough?

To put the question in a more precise context, I haven't got some kind of advanced physics engine the would create automatically something physically correct by default.


texts: I'm implementing a sort of isosurface extraction and theres a bunch of holes

texts:
i'm implementing a isosurface extraction algorithm losely based on dual contouring but theres a bunch of holes it looks like what i want though other than that
can you look at code and fix it maybe it's not much code
basically i'm looping through all the blocks and finding all of the changes in sign the interpolating the vertex and averaging all those out (as opposed to qef ) the problem is the second part of the code looking for vertexes to connect up get messed up ones when i have no changes in the block of the first code (i tested that with that bit of commented out code it just looks really jagged though)

darray3d<glm::vec3> verts(sidel);
    LOOP3D(sidel-1){
        glm::vec3 changes[12];
        size_t inc=0;
        LOOP2Da(1){
            if ((getpt(i+ia, j+ja, k+0,data,sidel)>0) != (getpt(i+ia, j+ja, k+1,data,sidel)>0)){
                changes[inc]=VertexInterp(0.f,glm::vec3(i+ia,j+ja,k+0),glm::vec3(i+ia,j+ja,k+1),getpt(i+ia, j+ja, k+0,data,sidel),getpt(i+ia, j+ja, k+1,data,sidel));
                inc++;
            }
            if ((getpt(i+ia, j+0, k+ja,data,sidel)>0) != (getpt(i+ia, j+1, k+ja,data,sidel)>0)){
                changes[inc]=VertexInterp(0.f,glm::vec3(i+ia,j+0,k+ja),glm::vec3(i+ia,j+1,k+ja),getpt(i+ia, j+0, k+ja,data,sidel),getpt(i+ia, j+1, k+ja,data,sidel));
                inc++;
            }
            if ((getpt(i+0, j+ia, k+ja,data,sidel)>0) != (getpt(i+1, j+ia, k+ja,data,sidel)>0)){
                changes[inc]=VertexInterp(0.f,glm::vec3(i+0,j+ia,k+ja),glm::vec3(i+1,j+ia,k+ja),getpt(i+0, j+ia, k+ja,data,sidel),getpt(i+1, j+ia, k+ja,data,sidel));
                inc++;
            }
        }
        glm::vec3 pos=glm::vec3(0.f);
        for (size_t ia = 0 ; ia < inc ; ia++)
            pos+=changes[ia];
        pos/=float(inc);
        //if (inc > 0)
            verts(i,j,k)=pos;
       // else
           // verts(i,j,k)=glm::vec3(i+0.5f,j+0.5f,k+0.5f);
    }
    LOOP3D(sidel-1){
        if (i > 0 && j > 0){
            bool solid1 = getpt(i, j, k + 0,data,sidel) > 0;
            bool solid2 = getpt(i, j, k + 1,data,sidel) > 0;
            if (solid1 != solid2){
                addquad(
                    verts(i - 1, j - 1, k),
                    verts(i - 0, j - 1, k),
                    verts(i - 0, j - 0, k),
                    verts(i - 1, j - 0, k),tris,solid2);
            }
        }
        if (i > 0 && k > 0){
            bool solid1 = getpt(i, j + 0, k,data,sidel) > 0;
            bool solid2 = getpt(i, j + 1, k,data,sidel) > 0;
            if (solid1 != solid2){
                addquad(
                    verts(i - 1, j, k - 1),
                    verts(i - 0, j, k - 1),
                    verts(i - 0, j, k - 0),
                    verts(i - 1, j, k - 0),tris,solid1);
            }
        }
        if (j > 0 && k > 0){
            bool solid1 = getpt(i + 0, j, k,data,sidel) > 0;
            bool solid2 = getpt(i + 1, j, k,data,sidel) > 0;
            if (solid1 != solid2){
                addquad(
                    verts(i, j - 1, k - 1),
                    verts(i, j - 0, k - 1),
                    verts(i, j - 0, k - 0),
                    verts(i, j - 1, k - 0),tris,solid2);
            }
        }
    }

picture of holes:


texts: How to convert UV position to texture atlas pos and reapply to UV in Unity

texts:
I'm trying to apply a texture from an atlas to a mesh by reiterating through the UV array on that mesh, but I'm a bit lost on converting the coordinates.

For example, if the texture required is at x,y pixels on the material texture atlas, how can I convert and get those coordinates and apply to the mesh? I'm redrawing meshes dynamically with a chunk loader for a voxel game, I have it down for square voxels but now when adding more complex meshes, need to know how to apply the texture to these.

I imagine the code would be something like, but I'm hoping someone can help me fill in the blanks:

   void UpdateMesh()
   {
       UVList.Clear();
       Mesh mesh = this.GetComponent<MeshFilter>().mesh;
       for (int i = 0; i < mesh.uv.Length; i++)
       {
           UVList.Add(GetUVTextureFromAtlas(mesh.uv[i].x, mesh.uv[i].y, voxelType);
       }
      mesh.uv = UVList.ToArray();
   }
  //converts UV position expected from mesh model to position on texture atlas
  Vector2 GetUVTextureFromAtlas(float x, float y, int voxelType)
  {
        Vector2 uv;
        Vector2 textureAtlasPos = GetTextureOffset(voxelType); // returns texture pos from atlas

      //not exactly sure what this would look like for code to convert
      //from the position on the atlas to the expected UV position based on
      //expected UV position (i.e. from 1,0 to whereever the texture is on the atlas)

        return uv;
  }


texts: Communication between Photon Cloud game and web server

texts:
I am creating a multiplayer game using Photon Cloud (Photon Unity Network). For storage of player data (profile, inventory, achievments) I use web server (asp.net mvc & sql server). How to organize the communication between the game client and the web server? I see two ways:

Use WWW class and send requests direct to web server:

var www = new WWW("http://mygame.com/api/user.get?id=1");
// Each time creates a new connection to the web server

Use Photon Cloud Webhooks and send requests through Photon servers:

PhotonNetwork.WebRpc("user.get?id=1");
// Photon Servers play a Proxy or Relay role between client and web server

— http://doc.photonengine.com/en/realtime/current/reference/webrpc

Which way do you recommend? The first way is simple but each time creates a new connection to the web server. The second way use one persistent connection between client and Photon server but there is a delay between connecting the Photon server to the web server.


texts: Android NDK - moving .so files from one project to another

texts:
I have a small project I've coded for Android that uses a small about of NDK/JNI code. I'd like to share this code between two projects but I'm having little luck so far. First off, I've tried to refactor off the NDK specific code into a library which I think link to both projects using

'project->java build path->source->link source'

and specifying the native library in there. Sounds good but it's wrong. The project from which I refactored the code still requires the .so library file in

MyOriginalProject\libs\armeabi\MyNativeLibrary.so

Removing that from the original project whilst still linking the source of the refactored library fails.

Secondly, creating a new project and attempting to use the NDK library I wrote by both including the source of the library and copying over the .so files from 'obj' and 'libs' into the root directory of the new project fails. It seems to pass

System.loadLibrary("MyNativeLibrary")

At least, it didn't assert.

The code gets as far as my first NDK call and then crashes without being caught by my exception handler.

Any hints would be welcome - such as foolproof ways to get NDK to load a library, typical gotchas and NDK debugging techniques.

Thanks in advance,

Tim.


texts: Am I going to regret using a color based collision detection system?

texts:
I'm just getting started build my first game with XNA (I'm experienced with C# but not games).

I'm building a pretty simple top down 2d shooter. I read this tutorial on using a color based collision system and it sounded really cool to me. http://www.xnadevelopment.com/tutorials/theroadnottaken/theroadnottaken.shtml

It means I can quickly make levels just using any graphics program and not have to define my scenery (walls, trees etc) in terms of collision boxes etc right?

However I can see that going down this path means that perhaps the calculation for determining whether fast moving objects like bullets intersect walls etc becomes more difficult potentially because you cant' do basic geometry intersection type calcs.

Is that right? Am I going to regret going in this direction if my game gets more complex over time? Worth just investing in the creation of a level editor to define my scenery in terms of geometry?

Any advice for a noob very much appreciated!


texts: Checking collisions on isometric grids with offsets

texts:
I have a isometric grid with sprites that are placed in this sort of manner:

x: 5
y: 7
OffsetX: 5px
OffsetY: 10px

This is - what i want to do is when placing a new sprite, check to see if they collide, i can do it quite easily by just checking the x and y but the offset confuses me on how i can efficiently check for a collision.

Dose any one have any suggestions on neat ways to efficiently check collisions with offsets?


texts: How can I clean up and smooth out procedurally generated terrain?

texts:
I am experimenting with procedural content generation, and starting with generating terrain from fractional brownian noise. The terrain produced looks fairly realistic, but has many artifacts and splotches of random terrain everywhere. Here are some examples:

How can I clean up the terrain so that it has smooth transitions from terrain type to terrain type without the scattered spots?


texts: Networked Physics - Interpolation Causes Physics Engine to Explode

texts:
A major issue I am encountering right now is that my physics engine (BEPU) and my network interpolation are conflicting with each other.

The player is a physics object, and so the physics engine updates it every update on the client.  When the client receives an authoritative position from the server, it replays the player's commands since the position was sent, and sets a "serverPos" variable in the player controller to that value.

Unfortunately, if a player should be on the other side of a bump in the terrain, the interpolation code will move the player into the terrain, which will cause loop of the player getting pushed back, the interpolation algorithm trying to push the player back in, and so forth until the engine literally explodes and gives me an NaN error.

My interpolation algorithm is extremely simple; each update, I keep track of how far the player has moved, add that to the interpolation target, and subtract away the distance interpolated from the last frame:

Vector3 serverPos;
Vector3 interpolationDistance;

void interpolate()
{
   serverPos += Position - lastPosition - interpolationDistance; // interpolated distance should not be factored into the target, as it will cause an infinite chain

   Vector3 preInterp = Position;

   Position = Vector3.Smoothstep(Position, serverPos, 0.3f);

   interpolationDistance = Position - preInterp;
}

Any advice on how to deal with this is greatly appreciated.


texts:
I'm creating a networked frame-based game (like Tetris battle), using the Java Sockets API, and right now my main concern is how to 'synchronize' the game state between two players. I've already implemented a multi-client chat, just to warm up.

In turn-based games (like chess), a simple solution is to send a 'move packet' and wait for the other player to send a 'received move' packet, so that the game can continue in a consistent state. Now, in a frame-based game (not real time though), I'm not sure if this is the best solution (the game will run in a local network, but I could scale it later).

Should I use this same technique? What are the other options? I'm new to networking, so I appreciate any help.


texts: Unity - Make a Mirror character of player in movement

texts:
What I want to achieve is :

I have a 3D game - with player in third person - and using cinemachine  Camera - imagine it like PUBG where you can look any where - the direction of the player does not change until the player is moving - the direction of character change in the same direction as camera

I want to make some sort of Shadow character as enemy , it will face the player - and mimic every movement exactly - not harmful

so when the player move forward - the other copy also move toward player - thus blocking his movement

so I want to achieve this using RigidBody - as Physics is needed to solve this puzzle

I tried different approaches- until I got to this code - it works OK - until I change the camera direction and then every thing is not working any more
     public Transform cam ;

    float speed = 10f;    //How fast the player can move
    float turnSpeed = 100;    //How fast the player can rotate

   public Animator animator; //Animation Control
    Rigidbody rigidBody; //Make sure you have a rigidbody

    void Start()
    {
        //Initialize appropriate components
        animator = GetComponent<Animator> ();
        rigidBody = GetComponent<Rigidbody>();
        cam = Camera.main.transform;
    }

    //No need for update function right now, physics work better in Fixed Update

    void FixedUpdate()
    {
        //right is shorthand for (1,0,0) or the x value            forward is short for (0,0,1) or the z value
        Vector3 dir =  (-cam.forward * Input.GetAxis("Vertical"))+ (cam.right * Input.GetAxis("Horizontal")) ;

        dir.y = 0;//Keeps character upright against slight fluctuations

        if (Input.GetAxis("Horizontal") != 0 ||Input.GetAxis("Vertical") != 0)
        {
                                                   //rotate from this /........to this............../.........at this speed
            rigidBody.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (dir), turnSpeed * Time.deltaTime);
            rigidBody.velocity = transform.forward * speed;
            animator.SetFloat ("Blend", 10);//Walk or run Blend works well here
        } else
        {
            rigidBody.velocity = new Vector3(0,0,0).normalized;
            animator.SetFloat ("Blend", 0);//Idle Blend works well here
        }
    }

    }


texts: Can Flash games packed for iOS and other mobile devices achieve reasonable performance?

texts:
I was thinking of developing a game in Flash, as a hobby/educational project.

However, I was hoping I could make it run on a smartphone, but a friend who develops in Flash says that in their experience things will move really slow on the likes of an iPad when the Flash packager is used. So slowly that you can't use it commercially for fast-moving games.

Has anyone else experienced this slowness? Is there a way around it or is the technology just not there yet?


texts: 2D physics on game object made up of components

texts:
Say you want to let your users create a 2D airship (side view) made up of components. One component could be a floating balloon, another could be a storage room, etc.

And say you want this airship to have physics applied to it as a whole, with each component playing a part in this. For example, balloons would take away from its down force and other compartments would apply down force to it.

At the same time, the whole airship works as a whole (or at least the only physical separation would be between floater components and the others, which apply weight), so physics are applied to it as if it was one body.

Now, how can this be managed? How can I customize a game object via a script, giving it different components with different weights, and have it behave like it was a single premade object?

I'm sorry if the question is simple, but I'm only getting started with unity. Thank you very much!

TL;DR: Customizable airship gameobject with different components that have different weights. How to make it behave as a single physics entity and manage its different components?


texts:
I have some difficulties with my vertex-fragment fog shader in Unity. I have a good visual result but the problem is that the gradient is based on the camera's position, it moves as the camera moves. I don't know how to fix it.

Here is the shader code.

struct v2f {
    float4 pos : SV_POSITION;
    float4 grabUV : TEXCOORD0;
    float2 uv_depth : TEXCOORD1;
    float4 interpolatedRay : TEXCOORD2;
    float4 screenPos : TEXCOORD3;
};

v2f vert(appdata_base v) {
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    o.uv_depth = v.texcoord.xy;
    o.grabUV = ComputeGrabScreenPos(o.pos);
    half index = v.vertex.z;
    o.screenPos = ComputeScreenPos(o.pos);
    o.interpolatedRay = mul(UNITY_MATRIX_MV, v.vertex);
    return o;
}

sampler2D _GrabTexture;

float4 frag(v2f IN) : COLOR {
    float3 uv = UNITY_PROJ_COORD(IN.grabUV);
    float dpth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, uv));
    dpth = LinearEyeDepth(dpth);
    float4 wsPos = (IN.screenPos + dpth * IN.interpolatedRay); // Here is the problem but how to fix it
    float fogVert = max(0.0, (wsPos.y - _Depth) * (_DepthScale * 0.1f));
    fogVert *= fogVert;
    fogVert = (exp (-fogVert));
    return fogVert;
}

Thanks a lot !


texts: How does the Unreal Engine transaction (undo/redo) system work?

texts:
I would like the transaction system to handle the create/update/deletion of some custom objects.

Then I can proceed as follow:

// Create custom object:
GEditor->BeginTransaction(FText::FromString("Create object"));

UCustomObject* CustomObject = NewObject<UCustomObject>(this, TEXT("CustomObject1"));
CustomObject->Modify();
CustomObject->AnotherCustomUObject = NewObject<UAnotherCustomObject>(this, TEXT("AnotherCustomObject1"));
// Should I call CustomObject->AnotherCustomUObject->Modify() ?
CustomObject->AnotherCustomUObject->AUProperty++;

GEditor->EndTransaction();

// Modify custom object:
GEditor->BeginTransaction(FText::FromString("Modify object"));

CustomObject->Modify();
// Should I call CustomObject->AnotherCustomUObject->Modify() ?
CustomObject->AnotherCustomUObject->AUProperty++;

GEditor->EndTransaction();

 // Delete custom object:
GEditor->BeginTransaction(FText::FromString("Modify object"));

// Should I call CustomObject->Modify() ?
// Should I call CustomObject->AnotherCustomUObject->Modify() ?
CustomObject->ConditionalBeginDestroy();
CustomObject = nullptr;

GEditor->EndTransaction();

Will all objects (and subobjects or subUproperties) correctly be recreated/updated/deleted on the first/second/third undo (and redo correctly handled)?

As far as I understood, those custom objects must necessarily be UObjects (with UProperties). How big is an UObject compare to a plain object? Could this affect performances? I will created hundreds of thousands UObjects (vertices of a mesh) in some transactions, is it a problem?

I already created a parallel undo/redo system with plain c++ objects which sync with the Unreal Editor transaction system, it works well ; the only thing is that the UE transaction manager does not know how big (in terms of memory) are my objects.


texts: top down game - checking, drawing enemy's line of sight area with obstacles

texts:
Examples of what i'm going to need:

I'm using cocos2d to draw a CCTMXTiledMap, on those tiles i'll have to draw the LOS cone.

How would i test if the player is within that cone, taking obstacles into account?
How would i draw the line of sight area on the map tiles, again taking obstacles into account, like in the examples above?

This is a re-post of a question i've put on stackoverflow.


texts: How to copy morphs from one SkeletalMesh to another in UE4?

texts:
I would like to enable modders to copy morphs from one SkeletalMesh to another.
I wrote simple Python script to do that. The inspiration came from here.
#Takes the last element of all selected stuff in the Content Browser
#Copies all morph targets from selection - excluding the last element - to the last element

#array = [ from1,from2,from3, ... , lastElementThatTakesAll]

import unreal as ue
from unreal import SkeletalMesh, MorphTarget

# create unreal class instances
editor_util = ue.EditorUtilityLibrary()
#material_util=unreal.Material()

# get the selected assets
selected_assets = editor_util.get_selected_assets()

lastmesh=selected_assets[len(selected_assets)-1]

morphtargets=lastmesh.morph_targets
print("lastmesh morphs: ")
print(lastmesh.morph_targets)

for morphlist in selected_assets:
    if(morphlist==lastmesh):break
    print("List: ")
    print( morphlist)
    for morph in morphlist.morph_targets:
        print("Morph: " )
        print(morph)
        morphtargets.append( morph)

lastmesh.morph_targets=morphtargets

It does work, I can see the sliders on the Receiver mesh in Persona...
The issue is it only works with duplicated meshes... Not very useful...
If I import the same mesh with different settings the morph target sliders don't do anything, even though the mesh topology is identical.
I wrote BP node to do the same thing, but the results are the same... sliders are present, but aren't doing anything.
bool UVictoryBPFunctionLibrary::AddMorphTargetToSkelMeshFromSkelMesh(USkeletalMesh* Receiver, USkeletalMesh* Sender) {
    auto senderMorphs = Sender->MorphTargets;

    for(auto morph : senderMorphs)
    {
        Receiver->MorphTargets.Add(morph);
    }

    return true;
}

I tried the RegisterMorphTarget function as well, but this one just crashed the editor.
Tried calling both in the construction script/beginplay as well.
bool UVictoryBPFunctionLibrary::AddMorphTargetToSkelMeshFromSkelMesh(USkeletalMesh* Receiver, USkeletalMesh* Sender) {
    auto senderMorphs = Sender->MorphTargets;

    for (auto morph : senderMorphs)
    {
        bool valid=Receiver->RegisterMorphTarget(morph,false);

        //GEngine->AddOnScreenDebugMessage(-1,15.0f,FColor::Red,"morph name:  "+morph->GetName());
    }
    return true;
}

EDIT:
This line causes the crash in the editor:
Receiver->InitMorphTargets();


texts: Creating a custom Editor Window using a Multi Column Header

texts:
Hey there I'm trying to use the MultiColumnHeader to create a tool to view materials in the scene, inspired by the light explorer. The problems I'm facing are two fold. First I can't figure out how to place the content of the  MultiColumnHeader in a scrollable view and secondly I can't figure out how to give the rows a different background color that alternates like in the light explorer. This is my OnGUI code:
 void OnGUI()
    {
        windowVisibleRect.width = position.width;
        windowVisibleRect.height = position.height;
        // draw the column headers
        var headerRect = windowVisibleRect;
        headerRect.height = columnHeader.height;

        float xScroll = scrollPos.x;

        columnHeader.OnGUI(headerRect, xScroll);

        // draw the column's contents
        for (int i = 0; i < columns.Length; i++)
        {
            // calculate column content rect
            var contentRect = columnHeader.GetColumnRect(i);
            contentRect.x -= xScroll;
            contentRect.y = contentRect.yMax;
            contentRect.yMax = windowVisibleRect.yMax;
            Rect rowRect = new Rect(contentRect.x, contentRect.y, windowVisibleRect.width,20);
            for (int j = 0; j < analyzerList.Count; j++)
            {

                Rect MatcellRect = columnHeader.GetCellRect(0, rowRect);
                Rect ShaderCellRect = columnHeader.GetCellRect(1, rowRect);
                Rect GameObjectsRect = columnHeader.GetCellRect(2, rowRect);
                rowRect.y += 25;
                EditorGUI.ObjectField(MatcellRect, GUIContent.none, analyzerList[j].mat, typeof(Material), false);
                EditorGUI.ObjectField(ShaderCellRect, GUIContent.none, analyzerList[j].shader, typeof(Shader), false);

                analyzerList[j].ShowGameObject = EditorGUI.Foldout(GameObjectsRect,analyzerList[j].ShowGameObject, "Show " + analyzerList[j].gameObjects.Count + " GameObjects");
                if (analyzerList[j].ShowGameObject)
                {
                    foreach (GameObject go in analyzerList[j].gameObjects)
                    {
                        GameObjectsRect.y += GameObjectsRect.height;
                        EditorGUI.ObjectField(GameObjectsRect, GUIContent.none, go, typeof(Material), false);

                        rowRect.y += GameObjectsRect.height;
                    }
                }

            }
        }

    }

If a Editor GUI guru could explain to me how to do it like I'm a child that would be great :). I don't do custom GUI stuff and most of this is beyond me.
As per requested I'm uploading two example images. One from unity and one I randomly found from the net. Note that I do not need the "stacking"(I dont know how to call them) headers from the second example. I do how ever require a vertical and horizontal scrollbar like in the second example.

And finally just for reference this is what my code does so far


texts: Multiple Sprites using foreach Collison Detection in XNA (C#)

texts:
Back again from my last question.  Now I was curious I use a foreach statement to use the same shot class.  How would I go about doing collison detection.

I used the tutorial here on how to shoot a fireball
XNA Development: Game Development for the masses.

I tried to put in several places a foreach to look at all of them to see if they have reached the borders of my sprite hero but doesn't seem to do anything.  If again some one might know of a good site that has tutorials to explain collision detection a little bit better that would be appriecated.


texts: Is it possible to use unnormalized texture coordinates from a GLES2 GLSL fragment shader?

texts:
I want to look up a texel from my GLES2 GLSL fragment shader using un-normalized texture coordinates (0-w, 0-h instead of 0-1, 0-1). The reason is that this texture is used as a look up table and I get precision problems with normalized coordinates.

I see that GL_TEXTURE_RECTANGLE is not supported wihtout extensions and neither is texelFetch(), so I have ruled out those options.

Thanks!


texts:
I am having trouble working out the math to transform the screen coordinates to the Grid coordinates.

The code below is how far I have got but it is totally wrong any help or resources to fix this issue would be great, had a complete mind block with this for some reason.

    private Point ScreenToIso(int mouseX, int mouseY)
    {
        int offsetX = WorldBuilder.STARTX;
        int offsetY = WorldBuilder.STARTY;

        Vector2 startV = new Vector2(offsetX, offsetY);

        int mapX = offsetX - mouseX;
        int mapY = offsetY - mouseY + (WorldBuilder.tileHeight / 2);

        mapY = -1 * (mapY / WorldBuilder.tileHeight);
        mapX = (mapX / WorldBuilder.tileHeight) + mapY;

        return new Point(mapX, mapY);
    }


texts:
i am working on a tile roguelike
i got some of the basics working using this tutorial
http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d

but i want to be able to create a map programatically instead of using the tiled editor

just add a NSArray of sprites/tiles to my CCLayer derived class or something, or should i make use of the CCTMXTiledMap class?

can anyone gimme some hints about how to do this? or know of a tutorial or sample code somewhere?

thanks a lot


texts: I am trying to use the AssetManager class in LibGDX and I understand how it works but I am trying to implement a loading screen. I have followed the AssetManagerTest.java file here, but I am having a hard time trying to figure out how to get it to work correctly. Can someone point me in the right direction? My goal is to load the assets (textures, sounds, fonts, ... etc) and update a bar with the percentage complete on the screen. I don't understand the ResolutionFileResolver and the Resolution[] in the link I provided. What are they for? My goal is to support a static class that can give me access to all of the assets I need in my game from any screen. Is there a preferred method to do this? Thanks.


texts:
Im trying to Load an RGB image (.BMP) into bullet's btHeightfieldTerrainShape

Im using a loader that creates a openGL height map, it stores the data in a vector float, but I cant get the btHeightfieldTerrainShape to accept it.

I changed the vector float into a float array which contains height data according to the debugger, when loaded it takes forever to load the terrain, and when its loaded it is a flat terrain.

It is alot of code, but I can add it if needed.

The Code


texts: LibGDX - How to draw a filled rectangle behind a text?

texts:
I'm new in LibGDX and I want to create a grid based game. Every square will have a rectangle and a text and the background color of the rectangles can change during the game.

The problem is when I draw a filled rectangle with ShapeRenderer, it always in front of the BitmapFont. How can I set the rectangle behind the text?

The code I use to draw the squares:

// Draw numbers and rectangles
for (int i = 0; i < map.length; i++) {
    for (int j = 0; j < map[0].length; j++) {
        String value = String.valueOf(map[i][j].getNumber());
        float offset = fontSize/3f;
        Rectangle rect = rects[i][j];

        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.setColor(150/255f, 150/255f, 150/255f, 1);
        shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
        shapeRenderer.end();

        // Draw font
        if (map[i][j].isActive()){
            fontActive.draw(batch, value, rect.x + offset, rect.y + offset);
        } else {
            font.draw(batch, value, rect.x + offset, rect.y + offset);
        }
    }
}

Thanks all!


texts: Traversing a pre-defined path with a delay in SFML - C++

texts:
I want the player to move smoothly & slowly through a vector of co-ordinates that define a path, below is an illustration of what i mean.

[P][ ][ ][ ][ ]
[.][ ][ ][ ][ ]
[.][ ][ ][ ][ ]
[.][ ][ ][ ][ ]
[.][.][E][ ][ ]

Once the path has been found the player should move between each tile with a visual delay, i have tried to code this behavior in a variety of ways but it seems that this a problem created by running Update/Render on the same thread, i think?

Here is what i tried

 if (pathFound)
 {
    for (auto path : waypoint_queue)
    {
        Move(this->character.getPosition(), path)
    }
    waypoint_queue.clear();
    pathFound = false;
} else {  }

Running this without a delay in an attempt to lerp between the co-ordinates of each "Next Tile" essentially teleports the player to the final node.

Running this with a delay of 1s for 10 tiles halts the program for 10 seconds then teleports the player to the final node.

How do i go about producing C#-like co-routine behavior that can update variables with a timed delay whilst also rendering them?

Thanks


texts: How should I traverse entities and components for their per-frame updates?

texts:
I am implementing a simple entity/component-based engine in C++ and am unsure about the best way to store references to entities/components and what the best way to traverse them each game step would be.

My current thoughts are to:

Store a reference to the parent entity of each entity in the game.
Instantiate the game engine with a root entity (e.g. a Scene entity).
Traverse all entities in the game starting from the root entity and call the update method.

My entity interface is such that each entity in the game will have an update method which will call the update method for each of the entities components:

class Entity
{
public:
    virtual void update();
};

However I don't think a tree traversal would be the most optimal solution - would it be better to store references to every entity in the game in a flat data structure and loop this every game step?


texts: Putting a Java/Slick game on your website?

texts:
I've made a simple little 2D game in Java using Slick and I want to embed it in my website. I'm just a little confused as to how to go about it, I'm guessing I need to export it as a WAR file?

Sorry if this isn't really specific but oddly enough I couldn't find any information on this subject. I think I may lack the basic vernacular to describe my question, because most of my Google and other searches turn up completely unrelated results any help would be appreciated, I just need a starting point.


texts: How can I calculate an octree node's depth from its location code?

texts:
The article Advanced Octrees 2: node representations states:

  The AABB (axis-aligned bounding box) of the node can be stored explicitly as before, or it can be computed from the node’s tree depth stored implicitly inside the locational code. To derive the tree depth at a node from its locational code a flag bit is required to indicate the end of the locational code. Without such a flag it wouldn’t be possible to distinguish e.g. between 001 and 000 001. By using a 1 bit to mark the end of the sequence 1 001 can be easily distinguished from 1 000 001. Using such a flag is equivalent to setting the locational code of the Octree root to 1.

The book Real-Time Collision Detection, Volume 1 by Christer Ericson states:

  The size of a node can be explicitly stored or it can be derived from the "depth" of the locational code. In the latter case, a sentinel bit is required in the locational code to be able to distinguish, say, 011 and 000000011, turning these into 1011 and 1000000011, respectively.

Both offer the following algorithm for computing the depth of a node:

int node_depth(unsigned int key) {
    for (int d = 0; key; ++d) {
        if (key == 1) { return d; }
        key >>=3;
    }
    assert(false);
}

How and why does this work?

The location code is a 32 bit word. That is, ... 011 and ... 000 011 might be equal, depending on what the remaining bits of the first location code are. using a sentinel, one has ... xx1 011 and ... xx1 000 011 and now they are different location codes.

What I don't understand is how can I get the depth of the nodes from the location codes and how does the sentinel help me with that.

Going back to the example above, ... xx1 011 and ... xx1 000 011, these words could be ... 000 001 011 and ... 000 001 000 011, respectively. Both cases have the sentinel bit, but since 001 (and any other xx1 combination) is a valid triple, all triples are valid, and there is no way for me to tell what the depth of the nodes is.

The only solution I've found is to store the depth of the node next to the location code, but that article and the book seem to indicate that the depth can be derived from the location code somehow.


texts:
We're developing a game in Phaser as a university project and have come across an obstacle. We need to detect when the mouse is over a line between two points. There are not a lot of lines, definitely fewer then 500. We were thinking of just checking it with line equations on every update call, but that might slow the game down. We haven't found anything useful on google. Should we just stick with the equations or is there a more elegant way?

Cheers


texts: How can I mod a Minecraft slime to be about the size of a full block?

texts:
I want to make the slime's size roughly the size of a full block,
I have tried some values but I'm not sure if any of those I tried fit the idea I have.
What would you recommend for the size of the slime which roughly matches or matches a block's size?


texts: Unity - Main manifest has  but library uses minSdkVersion='17'

texts:
I got this error message when trying to build and run for Android.

  Error: [Temp/StagingArea/AndroidManifest-main.xml:22,
  /Users/MNurdin/Documents/unity/TangoMotion/Temp/StagingArea/android-libraries/google-unity-wrapper/AndroidManifest.xml:3]
  Main manifest has  but library
  uses minSdkVersion='17'
  UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()

Where I can set android:minSdkVersion inside Unity? I'm using Unity5 right now. Please advice.


texts: LPD3DX10FONT::DrawTextA/W messes up the depth buffer!

texts:
why does calling this function mess up the depth buffer? I read somewhere that it cheekily changes the blend state, but to be totally honest I don't even know what that means. What is it doing, why is it doing it and what should I do about it?

Here is my code... instantiation:

RECT rct;
D3DXCOLOR fontColor = D3DXCOLOR(255,0,0,255);
LPD3DX10FONT m_font;
LPD3DX10SPRITE m_sprite;

and then...

rct.left=200;
rct.right=780;
rct.top=200;
rct.bottom=rct.top+20;

D3DX10CreateFont(device, 16, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS,     ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Verdana", &m_font);
D3DX10CreateSprite(device, 256, &m_sprite);

and THEN...

m_sprite->Begin(D3DX10_SPRITE_SAVE_STATE);

std::ostringstream oss;

oss << "This ruins the depth buffer!!!" << agents[0].State();

std::string test = oss.str();

m_font->DrawTextA(m_sprite, test.c_str(), -1, &rct, DT_LEFT|DT_NOCLIP , fontColor);

m_sprite->End();

as a side question, is there a more succinct way I can append variables to the string being written?


texts:
At any time, a game will likely have many objects rendering textures.
So what is a texture? an image for example?


texts:
When I get the depthnormals with the shaderreplace script, it just replaces all the shaders in the scene and uses the meshes geometry to calculate the normals, ignoring the normalmap textures applied on them.

How can I get the final rendered scene normals to a rendertexture like it appears in the editor windows normal debug mode that is used for deferred light calculations and ambient occlusion and such ?


texts: Is there a better way to set up an event system?

texts:
Event Systems are amazing, they make extremely unwieldy code tame and really allow for dynamic creation of games through easy communication of objects and the game loop. I am having a hard time with the efficiency of my current implementation. Currently my slight optimization of separating the lists of objects into the events they respond to has done wonders, but there should be more I can do.

Currently I have two methods:

Simplest : all objects are added to a vector
when an event is sent all objects are sent the event through it's handle_event() method
More complex : I have a map with string as it's key and int as it's value. When an event type is added, it's added to this map, with the int simply being incremented (there must be a better way)
the vector of vectors of objects then pushes back a new vector to handle that type of event.
When an event is called it simply calls the corresponding int in the eventTypes map to the type inside the vector of vectors of objects and sends that event to each object handling that event type.

These first method is quite slow (obviously) for lots of objects, but quite quick for very few of objects. Whereas the second method is quite quick with large objects that would like to handle different types of events, but slower than the first method per object with objects handling the same type of event.

Is there a faster (run time wise) way? Is there a faster way to look up an int from the string type? (Initially I had an enum, but it didn't allow custom types, which are necessary because of the desired level of dynamism.)


texts: How do I draw multiple irregular polygons with OpenGL ES?

texts:
In this post I was asking how to program a map of a Risk-like game.
Now that the map is pretty coded, both client and server-side, I'd like to finally draw the map.
I'll try to keep least broad as possible in this question, and also avoid XY problem.
So, my X problem is that I need an interactive map, based on (irregular) polygons.
Now, since this question would be really broad (there is a heavy number of possible solutions and libraries for a skilled programmer), this is how I imagined my Y solution:
Since the polygons have to be 10,  touch-interactive, filled with plain color, I think that OpenGL ES should go fine for me. I'm also attracted by Path and Point classes, but the problem is that

The map should be displayed for lot of different screen sizes, but at the same time it should keep its ratio, instead of appearing more large or more little in the Activity.

The polygons have to be drawn to fit each others.

Every polygon should be touchable and the event should differ from the others. Also their color could change depending of the situation.

I don't know if Path and Point classes would fit for this. My intent is more game-like than generic, so I think I'll stick with OpenGL ES solution.
The problem is that I don't understand

How can I map the polygons vertex and dimension for different screen sizes?

(considering we're talking about 10 polygons, there is a kind of environnment for doing this?)

Should I use triangulation or not? I've done lot of research but this point wasn't clear to me.

I followed Android Open GL tutorial, but it only shows simple polygons and alone, I'd need 10 with lot of vertexes and above all that can fit each others.
How can I do this?
EDIT: I also tried to follow this tutorial. This is an image taken from that one:

(source: xamarin.com)
To me instead, it's more little and near top-left corner. This is another trouble I'd like to avoid (as I said in point 1 above): my polygons should always fit the screen (and this is also why I want to use OpenGL ES).


texts:
Ideally I'd like a reference of the math involved, so I can start breaking down the problem.

The simplest thing I can deduce about this problem is that the part of the sphere that the user is currently seeing is a circle on the image that is located somewhere on the image, and the rest of the coordinates on the image are somehow mapped to 3D with a linear transformation.

Consider the following example:

If I rotate the sphere theta degrees on the Y axis (up/down) to the left, the sun will come close to the center of the sphere and the tree that is currently positioned in the center will be shifted to the left as the three on the left currently is. You can consider that the volume of the image is exactly enough to have the image completely wrap the sphere.


texts: How to do in Godot 2D: game screen in one viewport and minimap in another. Different sprites on each

texts:
The second day I google the tutorials, but nothing comes of it. All tutorials link to splitscreen demo, but it is made under the second Godot and does not work in the third.

The problem is this: I want to render the world in the main viewport and its simplified view on the minimap in another viewport using two different cameras.

In the main viewport the main AnimatedSprite node of objects should be rendered, and on the minimap there are only additional Sprite node of objects with their schematic view.

Tried to do:

Node2D
-ViewportContainer
--ViewportMain
--- Camera2D
--- World
----Player
-----AnimatedSprite # for main viewport
-----Sprite # for minimap
----OtherObjects
-----AnimatedSprite # for main viewport
-----Sprite # for minimap
-ViewportContainer
--ViewportMinimap
--- Camera2D

In code I assign main viewport's world to minimap's viewport:

$ ViewportMinimap.world = $ ViewportMain.world

For the main AnimatedSprite I set Light Layer #1, for the sketchy Sprite I set Light Layer #2.

And it does not work.

Firstly, nothing is displayed on the minimap. I don’t understand how to make it work. How to tell minimap's viewport to use the world from main viewport?

Secondly, I can’t find anywhere how to set the camera which Light Layer it has to display (in the three-dimensional Camera there is a Cull Layer parameter, but I don’t see it here).

Will this approach hit performance?

How to correctly implement minimap without need to modify it when you add new object to game?

How to correctly replace scenes when player moves from one to another if it child of the Viewport?


texts: How do you start modding a game without an editor?

texts:
I often come across very impressive mods for PC games that don't have an official editor, other development tools or its source code publicly available. (Take this amazing Multiplayer mod for Just Cause 2, for example.)
How do you go about creating mods for such games?
I'm not talking about replacing the odd texture or 3D model—that sort of thing seems fairly easy given tools to pry them out of game files and put them back in—but more along the lines of adding game behavior. (Tweaking settings files also doesn't count.)

Note that I'm not asking "how to create a mod", I just want to know where to start or where to go to learn.


texts: How to get image component from blueprint in c++

texts:
I have a dialog screenwith character icon and I need to be able to set up this image in code. But I don't know how to access this Image component (I put material instances in it).

.h

UPROPERTY(EditAnywhere) TSubclassOf<UUserWidget> widgetDialogBottom;
UUserWidget* widgetDialogBottomInstance;

.cpp

widgetDialogBottomInstance = CreateWidget<UUserWidget>(GetWorld(), widgetDialogBottom);
widgetDialogBottomInstance->Image("mi_dialog_2"); // Need something like this
widgetDialogBottomInstance->AddToViewport();

I made a class DialogBottomWidget:

.h

UCLASS()
class HOME_API UDialogBottomWidget : public UUserWidget
{
        GENERATED_BODY()

    public:
        void SetImage(UTexture2D* InTexture);

    private:
        UPROPERTY(meta = (BindWidget)) UImage* CharacterPreview;
};

.cpp

#include "DialogBottomWidget.h"

void UDialogBottomWidget::SetImage(UTexture2D* InTexture)
{
    CharacterPreview->SetBrushFromTexture(InTexture);
}

.. and then I made a blueprint based on that class. What should I do now?

I can get reference to image MaterialInstanceConstant'/Game/Materials/Faces/mi_dialog_2.mi_dialog_2', but how to put it to image component of the blueprint?


texts: DX11 StreamOut to Vertex Buffer from GeometryShader, can't clear Buffer?

texts:
I'm trying to use a geometry shader to continuously modify the positions of vertices, and save the modfied verts in a buffer.

I have two vertex buffers, one is bound to the IA stage / the vertex shader input, the other to the SO stage / the geometry shader output.
After I draw a frame, I swap those two buffers so that (ideally) the saved vertices get modified and saved by the GS again.

What actually happens though is this:
I have two buffers, outVB and inVB, both are empty, and an initial, vertex generating vertex shader is set

(Frame 1) Draw(..), the initial vertices are processed, saved to outVB, and drawn
I set inVB as the SO target, and outVB as the input vertex buffer
(Frame 2) Draw(..), vertices are read from outVB, processed, saved to inVB, and drawn
I swap the buffers
(Frame 3) Draw(..), vertices are read from inVB, processed, (apparently not)saved, and drawn
I swap the buffers
(Frame 4) the same output appears as in Frame 2
I swap the buffers
(Frame 5) the same output appars as in Frame 3

and it continues alternating between those two frames, which lead me to believe the buffers still contain the data they held the first time they were written to.

Which makes sense, as the GS can only append new data to the provided buffer.

So I tried releasing and recreating the buffer that is to become the new stream out target before swapping them (I couldn't find any way to clear it), which makes it produce 5 unique frames (including the initial one), and it loops over the last 4 frames, which makes no sense to me at all.

Destroying the buffer holding the old data and recreating it seems to work, since it progresses beyond the states of Frame 2 and 3, but if it worked how can it revert back to the states of Frames 2 and 3 after drawing two more?

my shaders are really simple so far:

struct GS_OUT {
    float4 Pos : SV_POSITION;
    float4 Col : COLOR;
};

GS_OUT VS(GS_OUT input)
{
    return input;
}

[maxvertexcount(10)]
void GS(point GS_OUT input[1], inout PointStream<GS_OUT> PStream )
{
    float4 position = input[0].Pos + float4(0.1f, 0.1f, 0, 1);

    GS_OUT output;
    output.Pos = position;
    output.Col = float4(1,1,1,1);

    PStream.Append(output);
}

float4 PS(GS_OUT input) : SV_TARGET
{
    return inut.Col;
}

My code for flipping the buffers (not neat, I know I could just flip the pointers then assign, but I wanted to make sure everything happened in exactly the order I want):

void swapVBs()
{
    static bool flip = true;

    UINT bufferstride = 2*sizeof(XMFLOAT4);
    ID3D11Buffer *nobuffer = NULL;
    UINT offset = 0;

    D3D11_BUFFER_DESC vbdesc;
    vbdesc.BindFlags = D3D11_BIND_STREAM_OUTPUT | D3D11_BIND_VERTEX_BUFFER;
    vbdesc.ByteWidth = 640*360*2*sizeof(XMFLOAT4);
    vbdesc.CPUAccessFlags = 0;
    vbdesc.MiscFlags = 0;
    vbdesc.StructureByteStride = 0;
    vbdesc.Usage = D3D11_USAGE_DEFAULT;

    if (flip) // SO Target == inVB, Vertex Buffer == outVB
    {

        //clear SO target
        devcon->SOSetTargets(1, &nobuffer, 0);
        //make inVB Vertex Buffer
        devcon->IASetVertexBuffers(0, 1, &inVB, &bufferstride, &offset);

        outVB->Release();
        device->CreateBuffer(&vbdesc, NULL, &outVB);

        //make outVB SO target
        devcon->SOSetTargets(1, &outVB, 0);

    }

    if (! flip) // SO Target == outVB, Vertex Buffer == inVB
    {

        //clear SO target
        devcon->SOSetTargets(1, &nobuffer, 0);
        //make outVB Vertex Buffer
        devcon->IASetVertexBuffers(0, 1, &outVB, &bufferstride,  &offset);

        inVB->Release();
        device->CreateBuffer(&vbdesc, NULL, &inVB);

        //make inVB SO target
        devcon->SOSetTargets(1, &inVB, 0);

    }

    flip = !flip;
}

and the draw code is nothing more than

devcon->DrawAuto();
swapVBs();

So I guess I'm asking...how do I properly clear a ID3D11Buffer?
Why in the world does releasing and creating a new buffer not give me an empty buffer?


texts: Share Image on Android Application from Unity Game

texts:
I've captured screenshot in my game when player dies. I've following code to capture screen shot.

RenderTexture rt = new RenderTexture (800, 600, 24);
        MainCamera.targetTexture = rt;
        Texture2D texture = new Texture2D (800, 600, TextureFormat.RGB24, false);
        MainCamera.Render ();
        RenderTexture.active = rt;
        texture.ReadPixels (new Rect (0, 0, 800, 600), 0, 0);
        MainCamera.targetTexture = null;
        RenderTexture.active = null;
        Destroy (rt);
        byte[] bytes = texture.EncodeToPNG ();
        Directory.CreateDirectory (Application.persistentDataPath + "/GameOverScreenShot");
        File.WriteAllBytes (Application.persistentDataPath + "/GameOverScreenShot" + "/DiedScreenShot.png", bytes);

I am getting saved screenshot using following code.

byte[] bytes = File.ReadAllBytes (Application.persistentDataPath +"/GameOverScreenShot" + "/BirdDiedScreenShot.png");

    Texture2D texture = new Texture2D (800, 600, TextureFormat.RGB24, false);
    RectOffset tempOffset = new RectOffset (5, 5, 5, 5);
    texture.filterMode = FilterMode.Trilinear;
    texture.LoadImage (bytes);
    Sprite sprite = Sprite.Create (texture, new Rect (0, 0, 800, 400), new Vector2 (0.5f, 0.0f), 2.0f);
    ScreenShot_Image.GetComponent<Image> ().sprite = sprite;

Now, I want to share this screenshot on android application. As per my research i have got following code for that, but it is returning blank image.

//instantiate the class Intent
    AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");

    //instantiate the object Intent
    AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");

    //call setAction setting ACTION_SEND as parameter
    intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));

    //instantiate the class Uri
    AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");

    //instantiate the object Uri with the parse of the url's file
    string destination = Application.persistentDataPath + "/GameOverScreenShot" + "/DiedScreenShot.png";
    AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse","file://"+destination);

    //call putExtra with the uri object of the file
    intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uriObject);

    //set the type of file
    intentObject.Call<AndroidJavaObject>("setType", "image/*");

    //instantiate the class UnityPlayer
    AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

    //instantiate the object currentActivity
    AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");

    //call the activity with our Intent
    currentActivity.Call("startActivity", intentObject);

What should I change in this??
Please help,
Advance Thanks


texts: How can I handle game-state updates in an MMO while the player is logged out?

texts:
I have a plan to build MMO strategy game like Goodgame Empire or Travian for Windows Phone. I want to program it in C# Monogame (because I have some good experience with it).

But I still can't figure out how to do game-server communication.

My plan is communicate with database through web service (WCF).

For example, if player build some building then the game saves information about that building through a web service method to a database.

But what if the player isn't logged in?

For example farms produce some food every hour. How to count how much food the player has when he logs into game after some time?

If you have some idea please let me know ;)


texts: How do I check for non tilted 2D rectangle collision?

texts:
I'm trying to find out how to check collision with different rectangles. Now the cubes I have have a x, y, height, and width to them.

So it might look like this on the screen:

And not like this:

Now I want to detect collision and then determine what to do. This is where I'm stuck. I don't know how to detect if two rectangles are inside each other or not and how to determine which side can the object not move to. If anyone knows what algorithm to use here to determine these thing help is much appreciated.


texts: C# Script file is not showing in Onclick Event in Unity 5.0.4f1?

texts:
I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me?

C# code:

using UnityEngine;
using System.Collections;

public class LevelLoader : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame

    public void LoadLevel(int a)
    {

        Application.LoadLevel(a);
    }

    public void Quit()
    {

        Application.Quit();
    }
}

Correct me where I am wrong. I am following this racing car game tutorial. At 7:58 he added this event.
Please help me!!!


texts:
This is a pretty simple question. If I was to use multiple images in a single texture for a 3D cube, how would I go about re-using each vertex (having 8 total vs 24)?
With a single buffer of 8 vertices, I don't see how I'd properly reuse the UV values.
Any help on that? I know it's not terribly clear, but I figured it was a simple question.
The 2D method is pretty easy, the next coordinates would be the same as the first (0,0 and 0,1 respectively).

However, the above 3D version has me quite befuddled.


texts: Can someone provide a simple algorithm for calculating an outcome based on User characteristics?

texts:
In these online games, say you are a person who has characteristics like:

level
strength
experience
defense
...

And now you walk into a room of 'others' that you want to e.g. recruit, how would you go about calculating this users ability to recruit?

Or any other common action in a online web game like a battle, or looking for items in the grass, or looking for food etc.

i.e. the ability or chances for success depend on the user's characteristics, and they get progressively harder as the user level ups etc.


texts: How do you spawn a component from a class in UE4?

texts:
Background
I'm working on a shooter game at the moment and I'm trying to spawn an Actor Component for the weapon currently in use, in order to have less Actors to keep track of.
The problem with this is that I can't easily switch out components on the fly, without making a separate function for each weapon.

Question
Is there currently any way to spawn a component with blueprints from a class like you would do with an Actor?


texts: When is the right time to save game data in a standalone game?

texts:
For standalone game, what's the best time to save game data, such as player's coins, level, skill data and so on?

Should the data be saved before quitting? Or whenever it changes? Or something else?


texts: What is the "correct" way to render to a cubemap using Vulkan?

texts:
After searching far and wide for the solution to this, the only one I have been able to find that verifiably works is to the render a face to a framebuffer and then use a memcpy to copy that framebuffer over to the respective part of the cubemap image.

This sounds stupid.

So I ask: Surely there must be some way to render directly to one face of a cubemap image, seeing as it's such an important feature in a whole lot of 3D rendering techniques. How do you do it?


texts: uv tiling and offset for uvs not min-max 0-1

texts:
For the purpose of the question, a unit = 1 meter.

So, I have a triangle strip that is 4x8 meters (for argument's sake; it is procedurally generated by player). I also have a texture which is 512x512px.

For normal UV mapping, I just make U 0 or 1 (depending on the side of the strip), and I make V a value normalized between 0 and 1, based on the distance "traveled" along the strip.

Then I set tiling based on the distance, and the texture. In this case, the tiling would be 2 along Y, since the texture is a square.

I am having trouble dealing with a scenario where I do NOT use UV 0 to 1 though. I only want to sample the "middle" of the texture,. such that the min/max of the UV coords are 0.0x0.25 to 1.0x0.75.

When I try to make this work, I notice that as I lay my strip (done by player in game; mesh updates continually during placement), the texture moves along the strip. I figure I need to adjust the offset, but I am having difficulty figuring out the formula to use to determine what the offset should be based on the tiling (which in turn is based on the length of the strip).

when the tiling is 1, there is no problem with the offset (0). A tiling of 3 is also correct with no offset. Same for tiling 5, 7, etc. Odd numbers basically. When the tiling is an even number though, or a fractional number, offset 0 no longer works. On top of that, the needed offset seems to change based on the tiling.

How would one go about calculating this?

In addition, if I lay two of these strips end to end, and I want the texture to be continuous; how would one calculate the offset based on the tiling/offset of the previous strip behind it?


texts: Getting path of right click in unity 3D editor

texts:
I want to create an extension for the Unity 3D Editor and have an custom asset type. During the process of creation this I recognized that I would improve the UX/usability if I can specify the path where I want to create the asset by using right click. But I fail to get the context path of the right click and I cannot find any hints on google or at the unity scripting api. Below you can see an image of the process I tried to describe above.

Here is the code that is responsible for handling the context creation "event".

[MenuItem("Assets/Create/Chat")]
public static void createChatViaMenu() {
    Chat c = Chatter.createDefaultChat();

    // This is the part where I want to insert the relative path.
    AssetDatabase.CreateAsset(c, "Assets/" + c.Title + ".asset");
}

If you need any more information please let me know.


texts: Blender exported model has reduced quality in Unity when normals applied

texts:
I know this topic comes up a lot in forums, however I have spent the last 2 hours googling it and can not find a solution for my specific problem...

I have exported this model from Blender, but when I import the model into Unity with normals set to "none" it appears as it does in Blender (see left image).

However, when I try to select import or calculate normals, it distorts the character mesh making it look less detailed and less human like (see right image).

I have tried messing with normals settings in Blender, tried changing quality settings etc. in Unity but I can not get it to look 1:1 with normals applied (obviously it needs lighting and shadows so I need it to have normals).

If anyone can provide assistance to fix this or a work around, I would really appreciate it a lot!


texts: Why boxCollider bound extents change when changing the size of an gameObject but doesnt in the script?

texts:
So, I have two players when I first made them they were with the default size Y = 1. After I finished the scripts I wanted to change their size but when I did that, the calculations use the size of Y = 1 and I don't understand why is that.

The code I am running is this:

public class Player1Controller : PlayersController {
    private Vector3 downMost;
    private Vector3 upMost;
    private float minY, maxY;
    private float halfHeight;

    // Start is called before the first frame update
    private void Start () {
        halfHeight = GetComponent<SpriteRenderer> ().sprite.bounds.extents.y;

        float distance = transform.position.z - Camera.main.transform.position.z;
        downMost = Camera.main.ViewportToWorldPoint (new Vector3 (0, 0, distance));
        upMost = Camera.main.ViewportToWorldPoint (new Vector3 (1, 1, distance));

        minY = downMost.y + halfHeight;
        maxY = upMost.y - halfHeight;
    }

    // Update is called once per frame
    private void Update () {
        float verticalMovement = Input.GetAxis ("Player1Vertical");
        MovePlayer (verticalMovement, transform);
        PlayerLimit (transform, minY, maxY);
    }
}

The PlayerLimits method is

public void PlayerLimit (Transform transform, float minY, float maxY) {
        float restrictY = Mathf.Clamp (transform.position.y, minY, maxY);
        transform.position = new Vector3 (transform.position.x, restrictY, transform.position.z);
    }

I assume the problem is either in the sprite bounds.extents.y or the restrictY but I don't get it.

This helps me with the Player limits, shown in the next image:

As you can see on the left side is the modified player with size less than 1 and on the right side is the player with the default size, the script is the same but the calculations are wrong. The left bar had to go till the end of the border but it doesnt.


texts:
When our game's ships move around, mouse aiming causes them to shake around a lot. The body being aimed is moved kinematically. I think we've narrowed it down to this block of mouse tracking code.

Demonstration of the glitch

You can see around 0:35 where I disable the mouse tracking code momentarily, the ship stops shaking.

    public static Quaternion RotateToMouse(this Ship ship, Transform transform, float ShipRotateSpeed)
    {
        // Generate a plane that intersects the transform's position with an upwards normal.
        Plane playerPlane = new Plane(Vector3.up, Vector3.zero);

        // Generate a ray from the cursor position
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

        // Determine the point where the cursor ray intersects the plane.
        float hitdist = 0.0f;
        // If the ray is parallel to the plane, Raycast will return false.
        if (playerPlane.Raycast (ray, out hitdist))
        {
            // Get the point along the ray that hits the calculated distance.
            Vector3 targetPoint = ray.GetPoint(hitdist);

            // Determine the target rotation.  This is the rotation if the transform looks at the target point.
            Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);

            // Smoothly rotate towards the target point.
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, ShipRotateSpeed);
            transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
        }
        return transform.rotation;
    }

We've got no idea whats going wrong, any help will be greatly appreciated.
thanks.


texts: Calculating the bounding box of a game object based on its children

texts:
2D game with Unity. Have a parent game object, with several children objects scattered all over the scene.

I want to calculate the bounding rectangle of the parent game object.

Let the black dots be the children objects. The red rectangle is the bounding box. I am not really interested in the position - I only want the dimensions of such box.

Of course, the bounding box should also consider the bounding boxes of the children... and so on.

How can I achieve this? I heard that Renderer has a bounds property... but my parent object doesn't have a renderer. And when I put one, the value is 0 anyway.


texts: How do I calculate sprites/frame usage on my platform's ram?

texts: I plan on building a 2d game for mobile and possibly pc. I also plan on using sprites/frames for the animation of my 2d game. What's stopping me from doing so is because I can't figure out if the sprites/frames containing the animation is gonna use up a lot of RAM on my device. Does anybody here know what I'm talking about?


texts: How to know if a model is composed of a group of models?

texts:
I've downloaded a model, and try to ungroup the model and learn how this model was made. However, the big model in the image below can not be ungrouped anymore.

I feel that this model is composed of a group of models, but I cannot ungroup this model and unlink it. Is there other methods to test if this model is a model or a group of models?

Thanks in advance.

  Full Size: http://i.stack.imgur.com/VF2SM.png


texts: Refactoring fighting game Movement class responsibilities

texts:
I'm a web developer, new to C# and trying to learn Unity. I've learned the C# syntax, I understand how to write working code, although I'm having a hard time understanding when and to what classes should I split my code.
At the moment I'm doing a simple 2D fighting game, similar to Mortal Kombat, I've started out with creating some basic sprites and basic scripts for the environment, like clouds spawning and moving (the action takes places on a rooftop), created a fighter character with animations and started with writing the movement script.
At this point, the Movement script deals with moving, jumping, animations (also triggers for punches and kicks) and player input (I'm using the new Input System), also I want to make the game a two player game, so the Movement script also checks if the the fighter is controlled by player 1 or player 2 and everything is crammed in this little Movement script, not that it's too large, it's just funny that a Movement script is doing so much and furthermore I'll need to add health and attacks (not just animations).
I think it's about time I refactor, my questions are:

Should I create a Character, CharacterController, CharacterManager or whatever script that inherits from MonoBehaviour and other scripts as simple C# scripts, or should all of my scripts inherit from MonoBehaviour and be attached as components to my GameObject with references to each other?

Should I have a separate script for my animations or should they be at their respective scripts as in Attack, Movement, maybe Jumping or Death, whatsoever?

What would be the best way or what would be the ways of managing my Fighter GameObject to determine if it is controlled by player 1 or player 2 and if I'll plan to add an AI for example? Should I have a PlayerController/AIController inherit from Character script, or have a separate AI class, or just have some variable to check against?

My problem with various tutorials is that most of them don't give a larger overview of the whole picture, most of them just focus on a single subject: movement, animations, spawning, pathfinding or some other concrete thing or term, etc. and don't show how they are intertwined together.


texts: How to associate a number to a button and get that number when the user clicks on the button?

texts:
I am creating buttons for each level through script as shown below

private void CreateLevelButtons()
{
    for (int i = 1; i <= no_of_levels; i++)
    {
        Button button = Instantiate(button_prefab);
        button.GetComponentInChildren<Text>().fontSize = 12;
        button.GetComponentInChildren<Text>().text = "Level " + i.ToString();
        button.transform.SetParent(content.transform, false);
        button.onClick.AddListener(() => OnClickLevelButton());
    }
}

In OnClickLevelButton() function I want to determine the level number of the button that was clicked. Is there a way to associate a number to a button so that i can access that number later when the user clicks on the button?