texts:
I'm trying to learn writing shaders. And I've pieced together something that is kinda working. I want to create a transparent glow around a sphere.
The problem I have is that I can't seem to alter the transparency of the glow.
I tried experimenting with ZWrite off but that doesn't give me the desired results.

The red part around the sphere is the glow. But I'm unable to change its alpha.
I'd would also like to change the "blurriness" of the glow. How would I do that?

EDIT

so I did some more tinkering. I've changed the blending to
Blend SrcAlpha OneMinusSrcAlpha and enabled ZWrite off. This allows me to change the alpha. The problem with this is that the inside of the object is also colored by the glow. I just want the glow around the circle. not inside.

Shader "Custom/HoleShader" {
Properties {
    _holeColor ("Color", Color) = (1,1,1,1)
    _glowColor ("Glow Color", Color) = (1,1,1,1)
    _glowSize ("Glow Size", Range (0.0,5)) = 1.0
    _glowOpacity ("Glow Opacity", Range(0,1)) = 1
}
SubShader {
Tags { "LightMode" = "ForwardBase" }
    Pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        uniform float4 _holeColor;
        uniform float4 _glowColor;

        struct appData {
            float4 normal : NORMAL;
            float4 vertex : POSITION;
        };

        struct v2f {
            float4 pos : SV_POSITION;
            float4 col : COLOR;
        };

        v2f vert (appData v) {
            v2f o;
            o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
            return o;
        }

        float4 frag(v2f i) : COLOR {
            return _holeColor;
        }
        ENDCG
    }
    Tags { "LightMode" = "ForwardBase" "Queue" = "Transparent" "RenderType" = "Transparent"}
    Pass {
        ZWrite Off
        //Blend One OneMinusSrcColor
        Blend SrcAlpha OneMinusSrcAlpha
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        uniform float4 _holeColor;
        uniform float4 _glowColor;
        uniform float _strength;
        uniform float _glowSize;
        uniform float _glowOpacity;

        struct appData {
            float4 normal : NORMAL;
            float4 vertex : POSITION;
        };

        struct v2f {
            float4 pos : SV_POSITION;
            float4 col : COLOR;
            float3 viewDirection;
            float3 normalDirection;
        };

        v2f vert (appData v) {
            v2f o;
            float4 pos = v.vertex + (v.normal * _glowSize);
            o.pos = mul(UNITY_MATRIX_MVP,pos);
            return o;
        }

        float4 frag(v2f i) : COLOR {
            return float4(_glowColor.rgb, _glowOpacity);
        }
        ENDCG
    }
}
}


texts: My 3D Shader wont render light direction correctly opengl/c++/glsl

texts:
This is what I'm doing:

vertex shader:

#version 400
layout ( location = 0 ) in vec3 vertex_position;
layout ( location = 1 ) in vec3 vertex_normal;

uniform mat4 ModelViewMatrix; //model
uniform mat3 NormalMatrix; //transpose(inverse(model)))
uniform mat4 priv_mat; //projection*view*model

out vec3 normal;
out vec3 position;

void main()
{
  normal=normalize(NormalMatrix*vertex_normal);
  position=vec3(ModelViewMatrix*vec4(vertex_position,1.0));
  gl_Position=priv_mat*vec4(vertex_position,1.0);
}

fragment shader:

#version 400
in vec3 normal;
in vec3 position;

uniform vec4 LightPosition; // light position: vec4(0,0,0,1);
uniform vec3 LightIntensity;

uniform vec3 Kd;            // Diffuse reflectivity
uniform vec3 Ka;            // Ambient reflectivity
uniform vec3 Ks;            // Specular reflectivity
uniform float Shininess;    // Shininess

vec3 ads( ){
    vec3 n = normal;
    vec3 s = normalize( vec3(LightPosition) - position );
    vec3 v = normalize( vec3(-position));
    vec3 r = reflect( -s, n );
return
    LightIntensity *
    ( Ka +
    Kd * max( dot(s, n), 0.0 ) +
    Ks * pow( max( dot(r,v), 0.0 ), Shininess ) );
}

void main()
{
     gl_FragColor = vec4(ads(), 1.0);
}

But when I run it, I get this:

Where the light doesnt just come from the wrong spot, but it also doesnt change when I move the planet around, like so

The diffuse value somehow gets the wrong direction? According to the example given (page 90), the diffuse is calculated by getting the dot(s,n), where s is lightposition-position, and position is (viewmodelvertex_position). But like you can see, the result doesnt shade the direction correctly.

Solution: The answer was matrix confusion all along. The problem was the ModelViewMatrix, and that It didnt have to be multiplied with view before being sent to the shader. The rest is just correct. Basically I was putting the "position" in the wrong space. Not multiplying with view before sending to the shader fixes it.


texts: Does every Entity in an XNA game need it's own BasicEffect instance?

texts: From what I see, the position/matrix is stored in the BasicEffect instance, so it makes sense to me that every object has it's own position matrix, but I'm not 100% sure it's correct to let every Entity have it's own BasicEffect instance, so I'm asking here.


texts:
I have followed the Unity Test Framework documentation to create an EditMode test assembly and a test script. When I try to test a function like Utils.SomeMethod(), the class is not recognized.
My IDE gives me the option to Reference Assembly-CSharp and use Utils which seems to successfully import the class as I gain autocomplete ability on the function names. But as soon as I try to run the test, the text changes back to red and I get a message that The name Utils does not exist in the current context.
What do I need to do to be able to test my class?


texts: Need Help Figuring Out Damage Calculations for Diablo RPG Clone

texts:
I'm building a Diablo clone using Unreal Engine 4 and have been having trouble wrapping my head around how the combat calculations should work. I copied a lot of the core stats from the original diablo game as a starting point.
Visited Websites:
How to develop RPG Damage Formulas?
http://diablo.blizzpro.com/2014/05/17/basic-theorycrafting-damage-formula/
https://diablo.fandom.com/wiki/Damage
http://diablo3blog.blogspot.com/p/diablo-3-damage-explanation-and-guides.html
So for the data model, I'm storing the character stats in a struct called PlayerStatsStruct.h. I also set some limits for how high the stats could go.
PlayerStatsStruct.h:
USTRUCT()
struct FPlayerStatsStruct {
    GENERATED_USTRUCT_BODY()

    FPlayerStatsStruct();

    UPROPERTY(EditAnywhere)
    FString Name;

    UPROPERTY(EditAnywhere)
    float TotalExperience;

    UPROPERTY(EditAnywhere)
    int32 Strength; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Dexterity; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Vitality; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Magic; // MAX OF 99

    UPROPERTY(EditAnywhere)
    int32 Agility; // MAX OF 99

    UPROPERTY(EditAnywhere)
    float Health; // MAX OF 1000

    UPROPERTY(EditAnywhere)
    float Mana; // MAX OF 1000

    UPROPERTY(EditAnywhere)
    bool Invulnerable;
};

Here is the struct I'm using for every monster.
MonsterStatsStruct.h
USTRUCT()
struct FMonsterStatsStruct {
    GENERATED_USTRUCT_BODY()

    FMonsterStatsStruct();

    UPROPERTY(EditAnywhere)
    FString Name;

    UPROPERTY(EditAnywhere)
    int32 Level;

    UPROPERTY(EditAnywhere)
    float Health; // MAX OF 1000

    UPROPERTY(EditAnywhere)
    float Defense;

    UPROPERTY(EditAnywhere)
    float AttackSpeed;

    UPROPERTY(EditAnywhere)
    float AttackDamageMin;

    UPROPERTY(EditAnywhere)
    float AttackDamageMax;

    UPROPERTY(EditAnywhere)
    float MovementSpeeed;
};

I made these formulas for determining the current Max Mana and Max Health like so:
MaxHealth = 218.f * FMath::Loge(Stats->Vitality) // MAX OF 1000 when Vitality is 99
MaxMana = 218.f * FMath::Loge(Stats->Magic) // MAX OF 1000 when Magic is 99
The main things that I'm stuck on are:

How do I determine the net damage inflicted on an enemy given both the Player Stats and the Enemy stats?
What exactly does defense do in combat?
How is dexterity related to defense?

I think at large the concept is this right?:
TotalDamageToEnemy = PlayerAttack - Enemy Defense
The problem is that the concept of defense is really abstract to me right now.
Thanks for your help.


texts: How can randomly paired players fairly select a map?

texts:
I'm developing a website for a board game that revolving around user-created boards.  Matches are currently created by selecting two people who have been waiting in a queue the longest and creating a match for them.  We will later implement matchmaking with specific users.

What is an appropriate way to select a map when a match is created with two random people?

Should one player be allowed to pick the map?
Should a random map be selected?
Maybe the players should rank a collection of popular boards by preference, then select the one with the highest average rating?


texts: How do I implement occluded lighting in a block-based 2D game?

texts:
I want to have 2D lighting that can be blocked by in-game objects. My game has a top-down view and all game objects are described by rectangles.

Let's say I have a 10x10 world and I place a light at 1x1 and walls all around that light. I want to be able to see the light source at 1x1, but not anywhere else, because it's blocked by the walls.

I've heard of casting light rays works, but how does that really work?


texts: How to build bullet (hit) damage detection in Augmented Reality to a real life person acting as an opponent?

texts:
I am building an Android AR game using ARcore 1.18 in Unity 2019.4.5f1 (LTS). Now I want to create something like bullet damage detection just like it is built in a normal Unity 3D game.
Of course, the biggest problem is how can I even detect the real person's hitbox like it is done in a normal game? I need to somehow be able to attach the bullet damage script to the body of the real-life person in real-time.
Has anyone tried this before? How can we achieve this? I understand if I might not get a spoonfed tutorial but some help towards what should I be doing to achieve this will be greatly appreciated.
I see some other FPS Augmented Reality games which either uses Laser Tag (Father.io) or Barcodes to scan the opponents. These are definitely some great ideas to create an FPS game experience but still, if possible, I want to try it with just the mobile camera without any external support. I am ready to bear some accuracy loss :)


texts: What is the right way to implement a loading screen in cocos2d-js?

texts:
We have two scenes that are loaded with heavy computation; a map screen and a puzzle screen. When we change the scene from A to B, the app gets stuck on scene A for a while before it renders scene B.

So to avoid confusion, we created a dummy scene with 'Loading...' written on it and then on it's onEnter function we change to scene B. The game now gets stuck on the dummy loading scene now instead. But the loading scene takes in touch inputs and the device's native button inputs and triggers it as soon as scene B enters. So the map scrolls if you swipe on the loading scene and puzzle takes input on tapping the loading screen.

Has anyone implemented a proper loading scene with cocos2d-js?


texts:
I'm writing a minecraft clone in C++ and need some assisting with the chunk generation. Because I only want to load chunks that are near the player, I have to load and unload chunks based on the distance to the player.

Of course the naive approach would be:

glm::vec2 playerChunkPos = VoxelWorld::getChunkPosition(*playerPosition);
for(int x = -chunkRadius; x <= chunkRadius; x++){
    for(int y = -chunkRadius; y <= chunkRadius; y++){
        glm::vec2 chunkPos = playerChunkPos + glm::vec2(x, y);
        //Generate Chunk
    }
}

But the problem with this is, that it doesn't start nearest to the player. To fix that I'd like to generate in "circles", more like "boxes" around the player.

Here is a simple illustration of what I mean: (The Center is the player position)

EDIT: Just saw that I skipped 1 iteration, whoops...

How would you reach that kind of iteration or anything similliar? I couldn't get anything to work..
All coordinates are signed and can have any value! The center/player can also be anywhere!


texts: Unity: how to release update without rebuild all game?

texts:
I have a game with a lot of asset (textures, 3d model etc), that reach 1 gigabyte of datas.

If i plan to release new prefabs and models, what's the best approach ? How to not create new builds and force my users to download everytem 1+ gigabytes ?

Thanks


texts: How To Display a friend list Using Play fab?

texts:
I m making a multiplayer game using playfab.

One player send  a friend request Second player then not display a player name?? I want the access(display) a player name??? see the referance,

Code:

ListingPrefab.cs

   public class ListingPrefab : MonoBehaviour
   {
      public static ListingPrefab Instance;

      public Text playerNameText;
    }

FriendRequest.cs

public class FriendRequest : MonoBehaviour
{
    public GameObject listingPrefab;   //btn
    public Transform panel;           //parent

    //Display Friend
    void DisplayFriends(List<FriendInfo> friendsCache)
    {
        foreach (FriendInfo f in friendsCache)    // I think problem is here
        {
            GameObject listfriend = Instantiate(listingPrefab);
            ListingPrefab templisting = listfriend.GetComponent<ListingPrefab>();
            templisting.transform.SetParent(panel, true);

            //PlayerPrefs.GetString("PlayerName", ListingPrefab.Instance.playerNameText.text.ToString());
            //PlayerPrefs.SetString("PlayerName",  ListingPrefab.Instance.playerNameText.text.ToString());

            Debug.Log("playername:" + templisting.playerNameText + friendsearch);
            //Debug.Log("helloone"+ f.TitleDisplayName);
            templisting.playerNameText.text = f.TitleDisplayName;                               // TitleDisplayName PlayFab unique username for this friend.
        }
    }

    void DisplayPlayFabError(PlayFabError error)
    {
        Debug.LogError(error.GenerateErrorReport());
    }
    void DisplayError(string error)
    {
        Debug.LogError(error);
    }

    //Getfriend
    List<FriendInfo> _friends = null;

    public void GetFriends()  //you can call button click
    {
        PlayFabClientAPI.GetFriendsList(new GetFriendsListRequest
        {
            IncludeSteamFriends = false,
            IncludeFacebookFriends = false
        }, result => {
            _friends = result.Friends;
            DisplayFriends(_friends); // triggers your UI
        }, DisplayPlayFabError);
        Debug.Log("Inside GetFriends");
    }

    //Add friend
    enum FriendIdType { PlayFabId, Username, Email, DisplayName };

    void AddFriend(FriendIdType idType, string friendId)
    {
        var request = new AddFriendRequest();
        switch (idType)
        {
            case FriendIdType.PlayFabId:
                request.FriendPlayFabId = friendId;
                break;
            case FriendIdType.Username:
                request.FriendUsername = friendId;
                break;
            case FriendIdType.Email:
                request.FriendEmail = friendId;
                break;
            case FriendIdType.DisplayName:
                request.FriendTitleDisplayName = friendId;
                break;
        }
        // Execute request and update friends when we are done
        PlayFabClientAPI.AddFriend(request, result =>
        {
            Debug.Log("Friend added successfully!");       //Add a friend
        }, DisplayPlayFabError);
    }

    string friendsearch;
    [SerializeField]
    GameObject friendpanel;

    public void InputFriendID(string inputfriendid)
    {
        friendsearch = inputfriendid;
    }

    public void SubmitFriendRequest()
    {
        AddFriend(FriendIdType.PlayFabId, friendsearch);
    }

    public void OpenCloseFriends()
    {
        friendpanel.SetActive(!friendpanel.activeInHierarchy);
    }

}

Prerequisites
SDK: Unity

The title ID is set in the PlayFabSharedSettings object (alaready i have)
The project can successfully log in a user  (alaready i have)
The title has at least two registered users  (alaready i have)

image:

I have 15 Player.

How To access a PlayerName??


texts:
I'm working on an RTS project, and I'd like to use the A* Project by Aron Granberg to navigate around obstacles. The problem is that the correct path is displayed in the scene, the unit is still walking forwards, but the unit just jumps to (0, 0, 0). As is, this as a workaround to have some progress in my build script.

Why is my A* object resetting to (0, 0, 0), instead of following its path?

I don't know where I made the mistake that leads to this behavior. Here is script responsible for the movement:

using UnityEngine;
using Pathfinding;
using RTS;

public class Unit : WorldObject
{
    public float moveSpeed;
    public Path path;
    public float nextWaypointDistance = 3;

    private int currentWaypoint = 0;

    protected override void Update()
    {
        Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;

        MakeMove(dir);

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

    private void MakeMove(Vector3 dir)
    {
        transform.position
            = Vector3.MoveTowards(transform.position, dir, Time.deltaTime * moveSpeed);
    }
}


texts: Contact friction for overlapping rectangles

texts:
I am currently developing a top-down "tabletop simulator" where you are able to drag, drop and rotate playing cards on a table. The cards are able to overlap but do not interact as of yet. What I now want to implement is that whenever a card is being dragged over another card, that the bottom starts moving as a result of the dynamic friction between the overlapping cards. Right now I am thinking of two ways to approach this:

Determine the area of overlap and use the center of mass of this area as the point where the friction force is acting on
Rasterize the cards and determine the overlapping raster and let the friction force act on these points.

Unfortunately I expect these methods to be computationally demanding and was wondering if there are more efficient methods out there. So far I have not found any material referencing this type of problem. I assume it relates to determining the area of contact for 3D objects and applying a friction force.


texts: Why isn't my background drawing to the screen?

texts:
Ok, So I have a game I have been working on for a few months now and I am now stumped beyond belief. My friend who has spent days working on this background gave it to me and I put it in my game. On the phone the background draws fine, on the PC the background draws fine but my tablet refuses to draw the background and I have no idea why. The game was pretty much built for tablet and I really need an answer because I want to release this to google play soon to make it worth while for the friends who put the effort into this game. Do any of you have any idea why this isn't working? The file for the background is pretty big is that the reason (2500x2500)?

Here is the code to the drawing method

    //Render Function When in Play Mode
private void renderPlayMode(){

    //Draw background
    background.render(mainBatch);

    foreground.render(mainBatch);

}

The background.render and the foreground.render are the two functions that cause the game to go black on the tablet. I really need an answer, please!

EDIT

Ok, so the code above is the code that screws up the tablet and makes the screen black. Because the foreground.render is the last thing that is drawn it makes the entire screen black and if I comment out that line the background.render just makes the entire background black and no drawing.


texts:
My friend and I are finishing up our first game right now and I have just discovered that even though he can make some decent music tracks, he has no idea how to make a sound effect. An explosion, for example.

How are sound effects made?


texts: Unreal Engine 4 AI Character Pawn Entirely Unresponsive to Movement Commands

texts:
I'm new to game development and to Unreal but I cannot for the life of me get my AI character pawn to move at all using any method I know.
I'm developing a 2d Sidescroller game using a Tilemap. I have made sure collision is set up with the map and tiles, the player character can interact with it all just fine, and I made sure to widen the collision thickness of the map so that the navmesh can properly appear (as seen with the green areas).
Nav Mesh loading. AI spawns in the air and falls down so I know he isn't overlapping with the ground

I've disabled and enabled collision for the static mesh cube component in the character pawn, but he still doesn't move.
The goal is to get him to follow the player when he sees him. The pawnsensing trigger works just fine, as I had it print whenever he sees him, and he even properly gets to the point of executing the "follow player" function (the print statement works).
However, using AIMoveTo fails every time. I've tried putting the player as the target, the player's worldLocation as a vector, and even an arbitrary point vector to the right of the AI but AIMoveTo fails every time.
I've deleted and replaced the NavMesh, and I've even tried completely skipping using AIMoveTo and just using Add Movement Input in both the AI Thinking Blueprint and Character Pawn Blueprint but neither make it move. I literally put an Add Movement Input function on the Pawn's event tick but it never moves.
Any suggestions?
Code:
AI Logic event is triggered every tick

Character Pawn Tick (for debugging). Does not cause the Pawn to move


texts: What is difference between AndEngine's three Cameras

texts:
I am new to game development. After observing some AndEngine code snippets, I am trying to figure out which camera would be best suitable for my 2D game. Either it's BoundCamera, SmoothCamera or ZoomCamera?

I just know that these three classes inherit Camera and bound Camera is used to limit camera area it can follow player.

Can someone tell what's the difference between these three cameras and when should I use one? It would be great if you can give some example. Thanks.


texts:
On the water demo supplied with Ogre3D's SDK, controls are set to actually control the camera and environment, but not actually the ogre head that generates the disturbances. I tried digging into the SDK code but couldn't find the actual pieces of code that allow customization of the controls (keyboard input). Maybe that's coming from the SampleBrowser application?

I intend to use that demo to generate the same Pygame/OpenGL water ripple effect I seek here: Pygame water ripple effect with the added benefit of the 3D engine. This is also targetted at a multitouch library that tries to stay away from Flash in support of harder reverse-engineering of the output binaries.

Bottom line, my question is, where are the keyboard controls bound to the scene on Ogre's SDK Water Demo? I am just starting in C/C++.


texts:
I am new to Cocos Creator and web game programming. I have build a simple game for the web, but I don't know how can I publish it. In the documentation files, it says:

  You only need to .zip scripts and resources in the game project and resource library, and then drop them into the designated release path

But I don't understand it. How do I publish a game for the web, using Cocos Creator?


texts: Models with more than one mesh in JMonkeyEngine

texts:
I’m a new jmonkey engine developer and I’m beginning to import models. I tried to import simple models and no problems appeared, but when I export some obj models having more than one mesh in the OgreXML format, Blender saves multiple meshes with their own materials (e.g. one mesh for face, another for body etc). Can I export all the meshes in one? I’ve tried to join all the meshes to a major one with blender (face joins body), but when I export the model and then create the Spatial in jme(loading the path of the “merged” mesh), all the meshes that are joined to the major doesn’t have their materials!

I give a more clear example:

I have an .obj model with 3 meshes and I export it. I have :

mesh1.mesh.xml , mesh2.mesh.xml , mesh3.mesh.xml
and their materials

mesh1.material, mesh2.material mesh3.material

so I import the folder in Assets/Models/Test and now I have to create something like:

Spatial head = assetManager.loadModel( [path] );
Spatial face = assetManager.loadModel( [path] )

one for each mesh and than attach them to a common node. I think there is a way to merge those mesh maintaining their materials! What do you think?
Thanks


texts:
OK I have a game that is similar to minecraft in a sense. Players can build castles block by block. I'm using Unity3D and Photon Network for my game and I was wondering how I would handle detecting if blocks have a support system to the ground. Here is the game in question. Let me know what are some solutions besides using rigid-bodies I've tried doing that and it has severe performance issues over a network. Thanks

Youtube Video of Game


texts: How can I run on multiple platforms using a custom engine?

texts:
Game engines like Unity and Unreal can run on mutiple platforms. I am wondering how they do this.

I have been using C++ and OpenGL for a while, and what I am looking for is resources to integrate something that will allow me run on different platforms without rewriting.  Something like LibGDX where you write code using a base API and then the API converts it to HTML, Android, iOS, et cetera. I am aware that I can use another engine instead of writing my own but I'm interested in the learning experience.


texts:
I have been wanting to solve the issue of movement once and for all... with all that I have learnt and read through, should be a piece of cake one would have thought... , seems it isn't.  Having rummaged through stackoverflow, I have found this link https://stackoverflow.com/questions/7312773/mathematical-vectors-and-rotations-topdown-java-game-dev-physics-problem and the bottom solution which explains how I exactly how I want acceleration to act as a 2D vector.

Moving on to the fact that the answer lies in the last post; that is having two vectors totaling to the acceleration vector, I am now faced with a simple yet unanswerable problem with the code I am using.  The problem lies in the fact that considering an angle of 0 and 360 degrees both pointing north respectively, I cannot for the life of me figure out why moving up will not keep the angle constant to 0. (apart from the fact that this angle is given through Math.toDegrees(Math.atan2(y, x)))

If we take this code for example ( a direct result of the last thread on stackoverflow )

double secondsElapsed = deltaTime / 1000.0;

double forwardDirection = velocity.angle() + 90;
double leftDirection = forwardDirection + 90;

double forwardAccel = 0;
if (up)
   forwardAccel = 100;
if (down)
   forwardAccel = -100;

double leftAccel = 0;
if (right)
   leftAccel = 100;
if (left)
   leftAccel = -100;

double fDir = Math.toRadians(forwardDirection - 90);
double lDir = Math.toRadians(leftDirection - 90);

Vector2D forwardUnitVector = new Vector2D (Math.cos(fDir), Math.sin(fDir));
Vector2D leftUnitVector = new Vector2D (Math.cos(lDir), Math.sin(lDir));

Vector2D acceleration = forwardUnitVector.scale(forwardAccel);
acceleration.add(leftUnitVector.scale(leftAccel));

Vector2D deltaV = acceleration.scale(secondsElapsed);

velocity.add(deltaV);
position.add(velocity.scale(secondsElapsed));
angle = velocity.angle() + 90;

the angle and motion with the upwards press is set to give acceleration on the x axis (which is fine considering my angle is 90 degrees pointing east).  Now realizing that we want a forwardUnitVector of (0,-1) (to get me poiting to the north) I was thinking something along the lines of a resulting degree of 270 (Math.sin(Math.toRadians(270)) = -1 which would be used along the y axis to create motion in the top direction.  However, having set the forwardDirection to 360 which would give me the desired result of forwardUnitVector(0, -1) I am given a velocity and an angle which acts as a rotation instead of a simple magnitude on the y axis.

Can anyone please explain to me why my concept of having motion towards the north is flawed?

Thanks for bearing with me!


texts:
I'm beginning with the 3D rendering in Monogame and i'm facing not a real issue because i already find a way to bypass it but more of a question.
I'm rendering a simple cube with 8 vertices like that:

_vertices[0] = new VertexPositionColor(new Vector3(-1, 1, -1), Color.Red);
_vertices[1] = new VertexPositionColor(new Vector3(-1, -1, -1), Color.Red);
_vertices[2] = new VertexPositionColor(new Vector3(1, -1, -1), Color.Red);
_vertices[3] = new VertexPositionColor(new Vector3(1, 1, -1), Color.Red);
_vertices[4] = new VertexPositionColor(new Vector3(-1, 1, 1), Color.Green);
_vertices[5] = new VertexPositionColor(new Vector3(-1, -1, 1), Color.Green);
_vertices[6] = new VertexPositionColor(new Vector3(1, -1, 1), Color.Green);
_vertices[7] = new VertexPositionColor(new Vector3(1, 1, 1), Color.Green);

But i'm also using an index buffer to draw each triangle for each faces and this is where my issue is. When i'm doing the following:

_indices = new int[] // 6 faces, each containing 2 triangles of 3 vertices
{
           0, 1, 2, 0, 2, 3, // front
           3, 2, 6, 3, 6, 7,
           4, 0, 3, 4, 3, 7,
           1, 5, 6, 1, 6, 2,
           4, 5, 1, 4, 1, 0,
           4, 7, 6, 4, 6, 5 // back
};

The render is perfect and every edge is rendered as you can see on this gif:

https://imgur.com/h7Kn4uH

But when i changed the order inside the index buffer of the back part, like the following:

_indices = new int[] // 6 faces, each containing 2 triangles of 3 vertices
{
           0, 1, 2, 0, 2, 3, // front
           3, 2, 6, 3, 6, 7,
           4, 0, 3, 4, 3, 7,
           1, 5, 6, 1, 6, 2,
           4, 5, 1, 4, 1, 0,
           4, 6, 7, 4, 5, 6 // back, update is here
};

The only thing that was updated is the order of the last column and the result is the following:

https://imgur.com/aCR3QXc

Why does the render is not done on the second case when the only change made is the order of two vertices ?
I know that I can do a rasterize state to render each side of a triangle but one solution is working without it, so i'd like to avoid using it.

Thanks!


texts: Need to boost the number of simultaneous players in single (existing) game with Unity3d

texts:
I have created a turn based multiplayer game (with Unity3d) in which three teams battle to finish constructing a cake before one another. The game mostly targets on entertaining kids at certain venues. It is free and is only running from time to time (it isn't online and does not run 24/7 like what we normally see).

The game consists of a few round that have two phases. Phase one asks for the joystick apps to enter their strategies (units to invest in construction and/or defense and/or attack) and send them to the server. This phase lasts for 30 seconds after which the second phase kicks in. Phase two is the MainGame talking to the server, getting all compiled strategies and rendering them on to the screen. The rounds follow one another until one of the teams finishes its cake. Kids love it!

The setup is rather easy. Players use a joystick App that they install on their iOS device enabling them to send strategies to the server. The MainGame is responsible of rendering the compiled strategies on to the screen. In between the Joystick Apps and the MainGame App is the server that glues everything up and manages the states of the game. The server currently runs on a free PlayerIO account that supports 45 players to be connected at the same time (actually 44 since one of the instance is the MainGame who does the rendering). When the game reaches its full capacity, all 44 joystick apps and my 1 MainGame app are connected to one single room. Everything works fine!

I now have this new client who wants me to boost the game so it can handle something between 1000 and 3000 players simultaneously. With you knowing this, here are my questions:

Should I stay with PlayerIO for my new and boosted version?
Is it just a matter of getting a bigger server? Can I still have one
single room with 3000 players joining it? If not, how should I handle
the weight?
How many players can normally connect to a single room (keeping in
mind I am looking for a way to connect as many people in a single
game at once… Not many games at once)? What’s the rules of thumb?
Being that the game will only be running a third of the time every
month (when my client’s starts it), how much can I expect to pay in
backend fees? (I really have a hard time knowing how much PlayerIO is
going to charge me with its new pricing).

Thanks in advance for your help!


texts: How forcefully should a single-player engine reject invalid data?

texts:
In a single-player game, when trying to build an entity out of components specified in external scripts, what do you think is more desirable to happen when one of the components is ill-formed:

Should the engine skip over that component and let the entity live in the game world with only the components that were well written?
Or should it not add the entity to the world at all if but one of the components is ill-formed?

Note, I'm not talking about logging the errors — that should come without saying — just about what should happen to the entity.


texts: What happens to deleted or added assets in your app when updating to a new version in the Google Play Store and iOS App Store?

texts:
So let's say I used Unity and built an app and uploaded it to the android and iOS app store, it is 100 MB and lots of people downloaded it. So now I want to update it to the newer version, however along the way I decided a lot of features were unnecessary so I remove about 50 MB worth of assets and the new build is 50 MB so I uploaded it to the respective app stores.

Will the people who already had my 100 MB app and now update to the new 50 MB version continue to have 100 MB of storage space taken up, even though the new one is half the size or will their app size be reduced to 5 MB according to the new build?

Essentially, how does app store updating work? Is the whole old app deleted and new one downloaded? Are matching files and assets retained and only differences in files and assets deleted or updated? Or are new assets and files just piled on top?

Additionally, for larger games, where the whole game is too big to be allowed on the app store, and where the player has to download more stuff once they have downloaded the game, how does it work? Is the additional, no-longer-needed content left on user's device kept there? Is it automatically removed?


texts: Migrating 2D game from immediate mode to VBOs

texts:
I am in the process of migrating away from legacy OpenGL calls in my 2D LWJGL game. Previously I would render each sprite using immediate mode, which was dead easy - bind the texture, add the vertices, and it's done.

Now I want to use vertex arrays. Ideally I would put the vertices for ALL my entities in one big array and render it in a single draw call. The problem? Each entity type uses a different texture, and glDrawArrays uses just one texure at a time.

Here are some possible solutions I came up with:

1) Create a separate vertex array for each entity

This is by far the easiest solution, but it somehow seems wrong to me, because it's so similar to using immediate mode. Doesn't this defeat the benefit of using vertex arrays?

2) Create a separate vertex array for each entity type

In other words, all entities that have the same texture will be rendered together. This isn't ideal as it would involve a good chunk of extra work and some extra effort on the CPU to separate the entities by type, and more importantly, would affect the z-ordering of the entities.

For example, it would be impossible to have a Tree that appears in front of one Squirrel but behind another Squirrel.

That is, unless I introduced a depth buffer, but I was trying to avoid this as it adds another level of complexity and, as I understand it, more work on the GPU (although that probably doesn't matter too much).

3) Combine all textures using a texture atlas

If I was able to use a single texture for all entities, I could use a single vertex array. However, there are 2 problems with this:

I have not been able to find a good library for creating a texture atlas at runtime, and writing this code myself would be non-trivial.
I am worried that some GPUs may have a prohibitively small texture size limit.

Summary

Would the first solution be viable / advisable?
Am I being foolish for trying to avoid using the depth buffer?
Am I missing something here? Is there a better solution?


texts: I have a music sound clip simply drag-n-dropped to my hierarchy. I also have other sound effects in my game. I want to pause/play background music on button press but only music, not all sound effects. How can I reach this music GameObject in C# code?


texts: I have such screen: very long world which I draw on stage and I need to scroll it. Now I move my camera in touchDrag() method. But I want to move my camera like I scroll it. E.g. I fling screen fast and my camera smoothly fly for some distance on y-axis. Just like it works in ScrollPane. How can I do this?


texts: How to tell OpenGL to use normals for lighting?

texts:
Let's say I have

    glGenBuffers(1, &vertexbuffer);
    glGenBuffers(1, &indexbuffer);
    glGenBuffers(1, &normalbuffer);

    glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER,sizeof(float)*numVertices*3,verticesArr,GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,numIndices*sizeof(GLuint)*3,indicesArr,GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER,normalbuffer);
    glBufferData(GL_ARRAY_BUFFER,sizeof(float)*numVertices*3, normalsArr, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
    glVertexAttribPointer( 0, 3GL_FLOAT,GL_FALSE,24, (void*)(0));

    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER,normalbuffer);
    glVertexAttribPointer( 1, 3GL_FLOAT,GL_FALSE,24, (void*)(12));

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexbuffer);

is it possible to tell OpenGl to use the normals in buffer for light "calculation"?

Basically I want to know how to say to OpenGl: "Here are my normals take them and make me nice lighting". Since I didn't find answer in google I posted my question here. Thank you for attention.


texts: SDL_PollEvent very slow on SDL2, but works fine on SDL1.2

texts:
I have this simple app that displays a screen and handles the quit event:

while( SDL_PollEvent( &e ) != 0 )
    {
        //User requests quit
        if( e.type == SDL_QUIT )
        {
            quit = true;
        }
    }

If I compile this with SDL1.2 it runs fine, the quit event is handled immediately.
However if I compile it for SDL2, then it takes ~5 seconds to get that event. And not just quit, but other events also, like mouse.

With sdl2 it takes ~95% of the cpu, while with sdl1.2 it's ~30-40%.
The cpu is dual core, 1.2 ghz (pandaboard).

I suspect something, but I'm not 100% sure:
I'm running this on ubuntu 12.04 which natively supports only sdl1.2.
So I had to compile sdl2 from source code, as it's not available in that ubuntu.

Could this be the reason? Or any other clues what might be wrong?
Thanks!


texts:
In Android development I found nine patch images very useful to draw images that have a fixed border. When the image is scaled the inner part scales, but the border stays at a fixed size.

I was looking for something similar in DirectX. Does anyone have information/pointers to nine patch images in DirectX?


texts: How do I add freeglut to a Visual Studio project?

texts: I am working on making a game for Windows in c++. I have previously made games for Ubuntu using freeglut, and I found freeglut for windows, but when I added it to the Configuration Properties\VC++ Directories\Library Directories tab in visual studio, visual studio complains about 'undefined reference' whenever I use a freeglut method. Does anyone have a solution?


texts:
How did they make the terrain in trine? I think they took a polygon approach. It doesn't seem that they used a heightmap because it is in all three vectors, or a voxel method because it doesn't have overhangs and cliffs. If it is polygon-based (I assume it is), how in the world would you texture the whole thing?

Notice how it's not very symmetrical and has lots of depth:


texts:
I'm using MJP's Cascade Shadow Map code and I'm having major issues with the shadows moving with the camera. Here a video to demonstrate what's going on. Also, is there a way to fix the dueling frustum issue? It's annoying seeing them pop in and out of corners of the screen.

Video of the shadows

c# and shader code


texts: What's the simplest way to make a sound stream from disk and play in OpenTK?


texts:
Suppose you have an arrangement of data for a terrain set up like this: terrain[layer][cart-x][cart-y]. Each location (ex. terrain[0][0][0] for the top left corner of the lowest layer) in the array simply stores -1 for air, 0 for water or 1 for dirt. How should I loop over this data to produce a "camera?" For example, given a focal point, world, and screen size, iterate over only the visible blocks and call the block-render function.

I have some semi-working Javascript, but I have several issues;

How can I find the minimal number of tiles to draw so that the screen edges are covered, while keeping the position centered on screen? I've gotten this done but it's messy.

When the layer depth varies, how do I properly account for that as far as offsets are concerned? Currently, I can make an offset calculation for a depth. But it doesn't carry to other depths. Like say, you are viewing an area where there is terrain at layer 15. The camera is offset by a certain amount to restore the focal point to center. But if you move to an area where the height is only 14, then you'll start to see a drop off toward one edge. This also happens when there is something much lower on the "forward" side.

How do I prevent drawing blocks that are completely obscured? This one is very important and should be seen as the priority of these, but I don't think I can move on to it yet.

Here's what I've made so far:

View working (hacky) example on Codepen

(Showing only what I think are the important parts here)

function screenPos(x,y,z)
{
  var op = {
    x: (x-y)*th,
    y: ((x+y)*th/2)-(z*td)
  };
  return op;
}

function drawTerrain(position, world, ctx, minElev, maxElev) {
  minElev = (minElev===undefined? position.z : minElev);
  maxElev = (maxElev===undefined? position.z+1 : maxElev);

  var cen = {
        a: position.x + position.y,
        b: position.x - position.y
      },

      max = { //Use testSize instead of canvas size so we can see overdraw
        a: Math.floor(testSize.y/th),
        b: Math.floor(testSize.x/ts)
      },

      startPos = {
        x: ((cen.a - max.a) + (cen.b - max.b))/2,
        y: ((cen.a - max.a) - (cen.b - max.b))/2
      },

      offset = screenPos(startPos.x, startPos.y);

  //account for testSize offset
  offset.x-=50;
  offset.y-=50;

  //regular offsets
  offset.y += th/2;
  offset.y -= (th)*minElev;

  ctx.textAlign = "center";
  ctx.textBaseline = "middle";

  for(var z = minElev-1; z < maxElev; z++) {
    for(var a = cen.a - max.a -1; a < cen.a + max.a +3; a++) {
      for(var b = cen.b - max.b -1; b < cen.b + max.b+2; b++) {
        if ((b&1) != (a&1)) continue;

        var x = (a+b)/2,
            y = (a-b)/2;

        drawTile(x, y, z, offset, world, ctx);

        i++;
      }
    }
  }
}

Some thoughts on possible solutions:  I think that at least one step of conversion between x/y and a/b could be removed here, as it's gotten all convoluted while trying to make things work. There are lots of things like that, I realize. The Codepen page shows exactly how thrown-together the current solution is. The only thing I'm interested in is fixing and optimizing the main loop and any methods/data necessary to drive it.

P.S. I didn't feel the need to include the drawTile function on this page as it has very little conditional logic, only basic stuff, and calls to the same screenPos function. That said, you can see it at the Codepen Example


texts:
I understand OpenGL is not thread-safe, but at the same time, Google seems to be giving me mixed responses.

I have a LibGDX game that functions normally, UI/rendering/logic on the same thread, everything is happy.

However, at a certain point, the user can initiate a process which involves a progress bar and lots of slow rendering (to off-screen FBOs). Right now I'm doing this on that one single thread, resulting in locking-up of the UI. I currently break out of the loop periodically in order release the lock on the UI every now and then.

What I'd like to happen is for another thread to be created at this point, and for all of the slow rendering to happen on it while the main UI/rendering/logic thread just displays a progress bar (without locking up of course).

Since both threads will be using OpenGL at the same time, is this possible?


texts: Detect which object conceals another one

texts:
I've searched for a while for a good solution and if I'd have found one I wouldn't be here. So there are the details:
I have been working on my 2D game using XNA, and I'm aware of the way XNA renders objects(If "a" was drawn after "b", it will draw "a" above "b").
In the game I'm making there's a character that is able to move left, right, up and down.
I'm, using Rectangle's "Intersects" method, when the rectangle on the character is placed on his feet, to detect collision detection.
I would also like the character to be able to move behind a house(Just like you can in real life, and the house will hide a part of the character that is hidden behind the house).
So far, all the things that I've mentioned are accomplished. Now, I would like to hear how would you recommend detecting whether the character is standing in front of the house, and hiding the part of the house that his standing in front of, or whether the character is standing behind the house. I understand it might be a little hard to understand, therefore I added a picture that will simulate the situation. (No I'm not the one doing the drawing)
Any help, advices, or criticism would be appreciated. Thanks ahead!


texts: How to store and retrieve user data in a multiplayer game

texts:
I am building a multiplayer game with a team and each player will have a multiplayer rank, a matchmaking rating (MMR), a username, and possibly a picture, a description etc.
We are planning on delivering the game on multiple platforms such as Steam, itch.io and GoG.

Since I am using Unity, how can I store and retrieve such data independently of the platform ? Is there a builtin service provided by Unity or do I have to create some SQL database and code all of the logic to use it ?


texts: Prefab with Sub-Elements Expansion Button Missing in Project Panel

texts:
I have been following along with a course. In this course a GameObject called "Path (0)" is added, this GameObject then has three sub-GameObjects ("Waypoint (0/1/2)"). In the tutorial, the guy drags the parent GameObject "Path (0)" into a folder called Paths in the Project panel to create a prefab. This prefab is shown with a handle to expand it. He then expands this prefab to see the sub-elements which can be dragged into the Inspector, as shown below (expand button highlighted with red box)

When I perform these operations, the Project panel does not have an expand button on the "Path" prefab (see below)

Why does my prefab object in the Project panel not have these expansion buttons?

I can get around this, by using the prefab instance in the Hierarchy panel, but this is a much longer process than being able to access the object from the Project panel.

Any help would be greatly received.


texts: Practical balance of "chance" video game mechanics

texts:
I've been a small games developer and designer for years, and I've recently begun working on more serious design documents for bigger projects.

A common theme I'm running in to is imbalance when it comes to "chance" RPG mechanics.
Critical Strike Chance. Chance to Hit/Dodge/Miss/Parry/Block so on.
The biggest problem in modern RPG games is factoring in Haste (Attack Speed), since it compounds so aggresivly with the other base mechanics.
Obviously, the more times a player attacks, indirectly increases their "rate" of critical strikes, or hits. This creates an immense imbalance, and most of the solutions come in the form of capping haste or utilizing diminishing returns or to killing the big stat increases.

As a designer and player, I don't feel this is a healthy way to deal with the issue. It's not a "fun" solution. Recently, gamers seen Blizzard's answer to this Haste issue in Diablo3, by halfing the stat increases on most all items.

Here is a practical example:

50% chance to critically strike, with 1 attack per second = on average 0.5 critical strike per second.
50% chance to critically strike, with 2 attacks per second = on average 1 critical strike per second.

The second situation is by far favorable, rather than increasing your Critical Strike Chance alone, since not only will you see more larger numbers (or hits in terms of a miss chance mechanic) per unit of DPS, you'll also be hitting more and games with Proc Chance mechanics also benefits.
More Complex games balance such things with Internal Cooldowns and Weighing the stats against each other, but often times Haste still comes out on top as being the supremely powerful stat.

Is it practical to instead use a Rate to decide weather or not something happens vs stat weights, capping and cooldowns?
My simplified example is:
Critical Strike RATE = Crit Chance / Attacks Per Second

The result is basically a simple stat weight system. Mechanics such a proc chances still benefit from Haste, however it may be easier to change the damage output of attacks and abilities to reflect the balance.
This keeps enjoyable haste mechanics in the game, which are fun to play. It also creates more depth for slower attack builds, rather than just an ability or proc benefiting from slow weapons.

Is this a near-sighted solution? Are there working examples of games currently on the market that don't cap or punish "haste" character builds?


texts: Is it possible to procedurally place objects in a non-gridded game?

texts:
I'd like to implement procedural world generation, but I don't want it to look gridded or blocky, where everything is obviously placed on an integer grid.

I know that you can do this in gridded worlds by inputting a square's x and y into a noise function, or similar, but is it possible to generate a more natural looking object placement using procedural methods?

This is in the context of an adventure game, if it matters.

Edit: I guess I should have been a bit more clear in my original question, but I'm mostly wondering about the actual placement of objects in game, e.g. trees, buildings.

Edit 2: I feel silly now. I typed up this question too quickly, and I didn't realize I was asking a yes or no question. I've reposted my actual question which asks, more specifically, how this can be done. Sorry!


texts: Should fields in components in an ECS use polymorphism?

texts:
I've just started to try and learn how to use ECS (Entity component systems), but I'm having trouble understanding the concepts behind components.

Should adding more types of components, or trying to make a component reusable through its fields be favored? For example, if I'm trying to give all entities a shape for collision detection, should I have a different component for every shape (RectangleComponent, CircleComponent, PolygonComponent), or should I have one ShapeComponent, and in there have a field which is of type Shape, with class Shape having subclasses Rectangle, Circle, and Polygon.

I'm unsure because using a Shape seems to be much more flexible and easier to implement systems, but it also feels like I'm violating the ECS rule of not having any functionality in components.


texts: I'm working on a shooter, platformer and everything is going okay so far, but I want to make some enemies that fly over top of the player and swoop around him. How can I make them fly? I've seen people suggest to change the world Gravity but that'd mess up the player. What's the best solution?


texts:
I'm working on Unity, and I'm trying to improve my water.
The water will be seen top down, and I want to apply a shader to it to make it better looking.
I understand the concept of distortion shaders and using noise to make the maps for the displacement.

However I don't know what is the best option when implementing this.

-When using noise for this effect, should I create this noise texture each drawing cycle?

-How can I keep the distortion animation smooth? Since noise is random, how can I make a smooth animation for the distortion?

-Be it calculated each cycle, or having a precalculated set of distortion maps, how does the shader recieve this info? Each cycle the shader recieves a different distortion map? Or does the shader hold all the distortion maps?

I have seen tutorials and guides, but they explain it on a high level, leaving a lot of gaps in the process, and not being very experienced with shaders, I don't know how to handle it.


texts:
I want to add random function into this script. If boxDestroyed is true, three items pop up. What i need is to give random number of items between 0 to 3.

    public GameObject[] items = new GameObject[3];
    public bool boxDestroyed = false;

void LateUpdate ()
{
    if (boxDestroyed == true)
    {
        Vector3 position = transform.position;
        foreach (GameObject item in items)
        {
            if (item != null)
            {
                //  int amont  = Random.Range(0,3);
                Instantiate(item, position, Quaternion.identity);

            }
        }

        Destroy(gameObject);
    }
}


texts: Javascript game to Phonegap for android game?

texts:
me and a friend of mine are in the process of building a javascrip/HTML5 game and I'm running into a few questions about the process of using converting it to an android game. I plan on using Phone gap as it appears to be fairly simple and does what I'm looking for it to do. I've done a little research, but there is still a few questions I have about the whole process.

Can I run the app offline? I want to be able to post the app to app store and allow people to download and play offline. Given the fact there will be no server requests can I make the game function offline?
As I make the game for the computer I'm relying on the keyboard as input to move around. Obviously, once I port it to mobile this won't be practical. What is the easiest way to go about doing this? I'm considering simply changing the game to have a click on screen which moves the character to that location or even a simple movement pad in the corner of the screen. Would these on screen clicks change correctly over to mobile.
Lastly, what is the easiest way to handle save data. On the computer side I plan to use HTML5 local storage to store game data. Does this convert to mobile or is there a better way?

I appreciate any help in this matter.


texts:
I have an FPS game that I'd like to make multiplayer. It would need to support multiple matches at once with about 10 players in each. However I want physics to be server-authoritative so that means running a Unity instance.

How do I have multiple Unity processes running on a server, creating/destroy them as needed, having players connect to the instance they need, and so on? How does this vary between uNet/Sockets/LLAPI/Photon/Bolt/etc?

There just seems to be an atrocious lack of information on Unity networking and when people ask online there's almost never any answer, or it's too vague to be useful.


texts: Are there any reasons to use Legacy (2.X) OpenGL?

texts:
The benefits are well documented of the Modern OpenGL 3.X & 4.X API's, but I'm wondering if there are ANY benefits to keeping with the old OpenGL, Or if learning OpenGL 2.X is a complete waste of time now no matter what?

Particularly I've wondered if using the OpenGL 2.X API is appropriate if the target platform had graphics hardware capable of only up to OpenGL 2.X. Would a driver update on said target platform allow programs compiled using the Modern OpenGL API's to be released on this old platform? If they both work, which would be faster?

Thanks


texts: Can not access GUIText in instantiated prefab

texts:
I have a prefab with the following component structure:

Block

Quad
RawImage
GUIText

When I instantiate it and try to access the GUIText, I get the output of 'null'.

Here is the code, I am using to access the GUIText:

public GameObject Block;

GameObject obj = Instantiate(Block, position, orientation) as GameObject;
GUIText myText = obj.GetComponent<GUIText>();
print(myText);

How do I fix this?


texts: MonoGame and normal windowed desktop application

texts: I am trying to move all my XNA projects to Monogame. But in project templates I found only XAML and horrible metro application template. Is MonoGame support creating application in good old windowed mode for Windows 8? If yes how?


texts: Is it must to use 3rd party framework to use to develop adobe stage3d game

texts:
I was searching for tutorials to develop games using stage3d. Every where I came across the articles/tutorials using the frameworks.

Is it compulsory to use the frameworks? or its very difficult to do it without frame works?


texts:
I'm a bit new to libGDX. My problem is ,in my code, only if I set the texture in the constructor of the Sprite instance, it will draw anything. My question is shouldn't it be working when I only call setTexture() when rendering? Or is there another way to render while changing the texture?

Following code doesn't draw anything.

public Sprite getSprite() {
    if (this.sprite == null) {
        this.sprite = new Sprite();
    }
    return this.sprite;
}

public void render(final float deltaTime, final SpriteBatch batch) {
    this.getSprite().setTexture(this.getCurrentTexture());
    this.getSprite()
            .setPosition(this.getPosition().x, this.getPosition().y);
    this.getSprite().setRotation(this.getRotation());
    this.getSprite().draw(batch);
}

Following is the working code.

public Sprite getSprite() {
    if (this.sprite == null) {
        this.sprite = new Sprite(this.getCurrentTexture());
    }
    return this.sprite;
}

public void render(final float deltaTime, final SpriteBatch batch) {
    this.getSprite().setTexture(this.getCurrentTexture());
    this.getSprite()
            .setPosition(this.getPosition().x, this.getPosition().y);
    this.getSprite().setRotation(this.getRotation());
    this.getSprite().draw(batch);
}


texts:
In main loop of PSM app:

public static void Main(string[] args)
{
    Initialize();
    while (true)
    {
        SystemEvents.CheckEvents();
        Update();
        Render();
    }
}

we are not actually controlling cycle length. I guess the delay is implemented internally in

SystemEvents.CheckEvents()

function since it's the only one that is no defined by us. My questions are:

Is my assumption right about how refresh rate controlled in app?
Is there any function (or app setting) in SDK that allows to set refresh rate to any other than 60 fps?


texts:
In follow up of my previous question: Limit the number of draw calls

I've lowered my draw calls to only 58 a frame!! But now I have another problem. I have 2500 cubes all drawn in the same position. I have no idea why. Everything that was done in my previous question works fine. This is my draw method that draws my chunk.

    public void Draw(BasicEffect effect, ThirdPersonCam cam)
    {
        device.SetVertexBuffer(vertexBuffer);
        device.Indices = indexBuffer;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            no++;
            pass.Apply();
            effect.VertexColorEnabled = false;
            effect.TextureEnabled = true;
            effect.Texture = grass;

            Matrix center = Matrix.CreateTranslation(new Vector3(-0.5f, -0.5f, -0.5f));
            Matrix scale = Matrix.CreateScale(1f);
            Matrix translate = Matrix.CreateTranslation(cubePosition);

            effect.World = center * scale * translate;
            effect.View = cam.view;
            effect.Projection = cam.proj;

            effect.FogEnabled = true;
            effect.FogColor = Color.CornflowerBlue.ToVector3();
            effect.FogStart = 1.0f;
            effect.FogEnd = 50.0f;

            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12);
        }

There might be some problems with the way the code is ordered in the method, but this is after moving things around. Changing the values in my DrawIndexedPrimitives line to vertices.Count and cubes.Count draws more cubes, but very strangely. There's 4 rows of 50 and then another row with just 10


texts: I'm working on my character menu for an RPG in Unity. I have my menu set up with different buttons for different categories. All is well, except when I re-size my screen, my layout is sized incorrectly. I need my GUI to respond to my screen size. Is there any information or a tutorial I can read?


texts: Can we develop a game for iPhone on Windows platform?

texts: Is it possible by any means to have a game developed for iPhone using the iPhone sdk on Windows?


texts:
I wonder how to make a sprite jump in pygame! Can anybody explain if possible?
Thank you!


texts: Generate different types of enemies with different randomness

texts:
What I want - I want to have some magic function getEnemyType(currentLevel), which will return, for example, a number. Number is enemy type, let's say, there are ten (10) types. 1 - the easiest, 10 - the hardest.
I can't even find the idea, where to dig, to get such algorythm: I give this magic function current level number and it calculate suitable enemy type with increasing and decreasing chanse of getting hard or easy enemy.
Example:

Level 1: function will generate random type from array of one
element: [1], okay
Level 2: generating random types from such set: [1,1,2], reason is to
have more easy and less hard enemies.
Level 3: [1,1,1,2,2]
...
Level 50: [1,7,7,9] (more 7s, less 9s for challenge, and little
number of 1s for fun)
Level 10000: [1, 10, 10, 10, 10, 10, 10]

Ideally game must be infinite, so I can just add enemy types to suit increasing difficulty.
Is this real? :)


texts: How to display an image stored in GPU video memory

texts: My platform is Windows PC and C++. I am using an image buffer in GPU video memory via CUDA. Is there any way to directly send the content to GPU for display? Currently, I am getting the content into system memory and then use API function (such as GDI, OpenGL. DirectX) to send it back to GPU for display. I wonder if there is a faster way to do this.


texts: How do I program procedural generation with objects that must fit together in specific ways?

texts:
I'm working on a game where I have to procedurally generate a large open room building. I'm using Unity, but I think this applies to any engine. The room is made up of different wall segments. What makes this difficult for me is the ends of the segments have to join with a similar end of another segment. There are 2 types of ends. Flat and angled. The purpose of the angled ends is to create an outside corner. Meaning for example a flat wall then turns into a hallway it would use angled ends to make the transition.
The method I tried initially was to define each segment type and what the follow up modules could be. Meaning SegmentA can be followed by: SegmentB, SegmentC, and SegmentD. Then I would randomly select which  of those to add and place it, then move on and repeat. It works ok, but I feel like there is a better way to do it. It's pretty unwieldy and is kind of prone to bugs. I also run into issues trying to close the loop and return to the original segment.


texts: GameObject.Find() finds objects in the old scene

texts:
I'm trying to create a simple scene transition. On entering a collider, there is a black canvas that's slowly faded in over the duration of 3 seconds. Then, a new scene is loaded, and the scene slowly fades from black to invisible. Now, I've almost finished it. However, I'm running into a small problem I cannot seem to fix.

The animation consists out of two text elements and one image. The hierarchy looks like this:

SceneLoader is an empty object, SceneFader is a canvas. Image is a black image stretched across the screen, and RegionName and RegionSubtext are two text elements that are filled as soon as the transition begins.

The code I'm using to load the scene is this:

private IEnumerator _loadSceneWithTransition(string sceneToLoad, Vector3 spawnCoordinates, string regionName, string regionSubtext) {
    this.screenFade.SetTrigger(SceneLoader.AnimatorTrigger);

    GameObject.Find("SceneLoader/SceneFader/Image/RegionName").GetComponent<Text>().text = regionName;
    GameObject.Find("SceneLoader/SceneFader/Image/RegionSubtext").GetComponent<Text>().text = regionSubtext;

    yield return new WaitForSeconds(4f);

    SceneManager.LoadScene(sceneToLoad);

    GameObject.Find("SceneLoader/SceneFader/Image/RegionName").GetComponent<Text>().text = regionName;
    GameObject.Find("SceneLoader/SceneFader/Image/RegionSubtext").GetComponent<Text>().text = regionSubtext;

    GameObject.Find("Player").GetComponent<PlayerMovementController>().spawnCharacterToLocation(spawnCoordinates);
}

Now, this doesn't work as I'd expect it to. The first part runs perfectly fine: The animation is started, the text is displayed and the scene changes. However, that's the part where everything breaks. As soon as the scene loads, there is no text. Also, the player position is not set to where it should be.

I really do not know why, the only reason I could think of was that the script was called in the first scene, and therefore, the GameObject.Find() calls return the elements in that scene, not in the currently used one (actually, I'm fairly sure of that because GetInstanceID() returns the same for both calls). Now, the problem at this part is that I do not know how to make that work properly. One idea I had was to do try and fetch a new instance of the script with something like: GameObject.Find("SceneLoader").GetComponent<BaseSceneLoader>() and work with that, but then I remembered I still need GameObject.Find() for this, which would probably yield the result of the old scene, so it's not helping at all. On top of that, I'm not even sure if that is the actual problem.

I'm kinda out of ideas here. I also do not know what's the best practice in that situation, and I couldn't find anything meaningful on DDG either.

Lastly, I've created a small video clip showing off the problem. I hope this helps in identifying the issue.

https://imgur.com/a/1eS8rcG


texts:
I am making a 2D RPG in XNA, and I want to be able to have basic cutscenes, kinda like those in the handheld Pokemon games.

What is the easiest way to do this? Sorry for the vagueness of my question, but I'm new to game development, and nothing I've found says how to do this.


texts: What 3d mesh formats usable with DirectX10 are there?

texts:
I want to load a mesh into my game (written in C#, if this matters) but am not sure what mesh format to use. What mesh formats are there, how easy/hard it is to load them into DirectX10 and what's the difference between those formats?

Or is it best to write my own mesh format?


texts: Unity - Vector3.Reflect not reflecting correctly

texts:
I resolved the question on how to draw a line, so here is the result:

https://www.dropbox.com/s/hvc9yr3jjbqdv7r/dc.jpg?dl=0

So, now I want to create a line that shows the possible bounce off the wall (and the other ball).

Some suggested I use the Reflect method but it did not work, here is how I implemented it, script is attached to the white que ball:

//
        Ray ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit2;

        //
        if (Physics.Raycast(ray2, out hit2, 100.0f)){

            //position of white wall
            Vector3 startPos = transform.position;
            //cliked position, translated to the table plane
            Vector3 clickPos2 = new Vector3(hit2.point.x, hit2.point.y, transform.position.z);
             //get direction from ball to clicked position
            Vector3 direction = Direction (clickPos2 - startPos);

              //so I simply should do I reflect, it gives me a bit odd results
            Vector3 reflectDir = Vector3.Reflect(direction, hit2.normal);

            //finally im drawing the line
            lineRenderer.SetPosition(0, startPos);

            Vector3 forward = transform.TransformDirection(direction) * 100;
            lineRenderer.SetPosition(1, forward);

              //reflection?
            lineRenderer.SetPosition(2, hit2.point);

            lineRenderer.SetPosition(3, reflectDir);

Here is what this code gives me:

https://www.dropbox.com/s/9dfb3vyqmbknzes/gb.jpg?dl=0

Any ideas on how to make it work?

Mirza


texts:
I am trying to use a component based pattern on my new project. The last projects I did the old fashioned way. Base class and derive from that until your brain hurts. This time I wanted to do it on a new way with a component approach.

Component Base Summary: The idea is that you build components and compose your objects out of different components e.g. the Player class holds GraphicComponent, PhysicComponent, InputComponent, CameraComponent, ScriptComponent and so on, but an decoration object like a plant only has GraphicComponent and maybe PhysicComponent.

I like this approach. I tried to implement it but I have a little understanding issue.

As far as I understand it, each component has the logic for itself in it, and barely know of other components. But this is the part I don't understand: Let's say we have a RenderComponent which holds the logic for rendering. But each concrete object like a player, a plant an UI-element and so on has to be rendered on a completly different way. The player hast special effects and different animations, the plant is only a sprite and the ui element is a combination of both. Do I put the logic for every different rendering in the RenderComponent all at once e.g. RenderPlayer(), RenderPlant(), RenderUIElement() which does not make sense to me or do I make an Interface out of the RenderComponent and create a specific RenderComponent for each concrete objects like PlayerRenderComponent : IRenderComponenent ?

Update

After reading the Answer from Nick, I did a quick UML-likish diagram to clearify if I got the idea/structure right. The diagram is just an example with a pseudo UML-like diagram an some pseudo example constelations. The Idea is, that the concrete composition objects holds and treats their component as a data structure. They set it, alter it, and read from it to do it's logics. They also can compare Components of other concrete objects for convience and provice their components to higher systems (like managers)

Update 2
After some discussion and a bit of confusion due opposites arguments, I started to google with new keywords I got from the comments and found an article which helped me understand how the system is glued together.


texts:
I have made an item database that takes keyed values from a database script then assigns them to an item class, then stores that item class in a List variable.

This works fine but I have come across something that I see as potentially troublesome. For every unique effect, I have to make another keyed value and apply it to all the existing collections in the database.

I want to make it such that an item can hold only 6 special values(physical damage, magical damage, armor, heal, etc) but with this method, I don't know how to tell the script which value goes to which special effect.

Below is a template item from the database file. I use GRFON for this.
See how I have written down all the possible damage types but for special values, I made 7 only with 6 of them being generic.
The damage types can easily be assigned but when it comes to the special values, I have a hard time assigning magnitudes to special effects.

{
iD: 0
name: Template
category: Null
type: Null
subtype: Null
values: {
    physical: 0, magical: 0, hot: 0, cold: 0, electric: 0, dark: 0 }
specialvals: {
    spMag1: 0, spMag2: 0, spMag3: 0, spMag4: 0, spMag5: 0, spMag6: 0, spDuration: 0 }
special: none .
properties: {
    mass: 0, durability: 0, maxdurability: 0, charge: 0, maxcharge: 0, accuracy: 0, useRate: 0, reloadRate: 0, range: 0 }
description: This is a template item.
equippable: 0
usable: 0
stackable: 0
maxStacks: 1
count: 0
rarity: 0
price: 0
uID: template
}


texts: Calculate damage values from bullet velocity and size

texts:
I'm trying to make a top-down game using Javascript and Pixi which involves multiple different guns.
Instead of giving each gun an individual damage value, I wanted to calculate the damage by the bullet's dimensions and velocity as it leaves the gun (which is all available on Wikipedia).
However, I'm having issues where despite some damage values looking okay (e.g. UMP-45 has about 40, Mac-11 has about 22, TEC-9 has around 35 and Glock has about the same) some values are too high to offer a challenge to the player (AK-47 has 110, M4A1 has 220, Desert Eagle has 100+).
The current calculation I'm using is:
\$ \frac{velocity \times bullet\ length}{1000} \times \frac{bullet\ radius}{2}\$
Or in pseudocode: (velocity*bulletLength/1000)*(bulletRadius/2)
Anyone have any ideas for tackling this issue, or is it best to just use straightforward values? The game would be a horde-like sandbox game, so the damage values can't be too low or it would be almost impossible.


texts: Find nearby users by real world location in Unity

texts:
I am looking to add a feature to my mobile game (IOS and Android) to let users connect to trade with users nearby in a certain radius based on the real world geolocation. Whats the best approach to find nearby users who are also running the game right now?

I have looked into using bluetooth using assets such as this: https://forum.unity.com/threads/android-bluetooth-multiplayer.188667/ but it seems like there is nothing for bluetooth multiplayer between android and IOS.

There is plenty of AR tools like this one: https://cloud.google.com/maps-platform/gaming however non seem to have the feature I am looking for.

Or perhaps if there is no existing solution for this. I have to share and compare player locations via a game server. However I have no idea what my first steps would be for that.


texts:
Can any of you please demonstrate a simple example on how to use groups in libGdx ? so if i move the parent, then all the children will move with it and same goes for rotation and scaling.

I looked for tutorials and example online but it seems that the latest version of libGdx did some changes to the Stage class.

Thank you


texts:
I am making a speed meter of car. Its pretty simple when ever speed increases or decreases the meter pin moves accordingly. I have done the movement part of pin but I am unable to get a smooth movement.

    public Image meterPin;

    const float maxPinAngle = -116f;
    const float minPinAngle = 16f;

    float meterMinSpeed = 10f;
    float meterMaxSpeed = 210f;

    void Update()
    {
        changeMeterSpeed();
    }
    void changeMeterSpeed()
    {
        meterMinSpeed = userSpeed;
        meterMinSpeed = Mathf.Clamp(meterMinSpeed, 0f, meterMaxSpeed);

        meterPin.transform.eulerAngles = new Vector3(0, 0, getTransformRotation());
    }

    float getTransformRotation()
    {
        float totalAngle = minPinAngle - maxPinAngle;

        float speedNormalized = meterMinSpeed / meterMaxSpeed;

        return minPinAngle - speedNormalized * totalAngle;
    }

The userSpeed value is calculated in another function in this script. The only issue is that the movement is not smooth. Any ideas if I can fix the smoothness issue in this script.

EDIT:

Here is a gif to explain whats happening.

Thanks


texts: Parallel Storylines - Underused Francise Characters

texts:
One Hero Rule: Video games have only one protagonist. Example: in an rpg, party members are not seen in a field map, or they just follow you. Their role is "cannon fodder" tier, meaning who the hell cares if it dies. I never added it to my party anyway, following the min max gamefaq guide telling me to remove all its equipment beforehand. You end up with a video game that has only a single actor that plays 1000 tropes, in real life each person plays ~5 tropes at most. This is a bug caused by a single protagonist rule, i want to eliminate this rule through smart game design.

The problem is, in movies you can depict unlimited different characters and the story continuity never breaks, but in a video game leads to loss of context, can it be done?
conclusion: video games are an inferior mean of screenplay.

In Suikoden / Breath of fire 4, each chapter is devoted to a specific protagonist view, this is nice concept however it can get ankward...

Loss of context:
You would end up progressing their individual character storylines a little bit, but since you "switched context" to another protagonist, you lost track of what the other protagonist did, you no longer remember the progression of the story. This will never work... Especially if switch happens very frequently and the battles last too long.

Game Balance: Extra party members do not add to battle effectiveness:
in suikoden by endgame you have 200 party members but they are irrelevant since random encounters use only 4 party members. It is better to keep the same cast throughout the game and become overleveled than spread xp to never used party members.

Android "Pimp your money" games fixes this by adding a 30 min cooldown to each party member. This is nice, but they don't have story... Also this mechanic enforces a "play everyone a little bit", disables free choice of which party member to pick, amplifying your loss of context.

Why i want this? imagine a game like kingdom hearts where each party member gets its own storyline.

Questions:

1) Need Story-Telling Methods that avoid loss of context.

2) Need Battle Game Balance Rules.


texts: Is there a good cross-platform C++ vector graphics library out there?

texts: I'm making a game and want to use vector graphics. I started re-coding it using Cairo and the performance is horrific. So, I'm looking for a different library. It needs to be for C++ and cross-platform (e.g. no Direct2D). There's another question someone asked before like this, but there weren't any suitable answers. There's got to be something...?


texts:
I'm trying to get started modding Minecraft. I opened up the minecraft.jar file in Eclipse, but it doesn't contain what I expected.

In this tutorial the presenter decompiles minecraft.jar and finds things like armor and blocks packages, but when I put my minecraft.jar file (from [user]\appdata\roaming\.minecraft) into Eclipse, I only see Apache and Ydggrassil authentication and such.

What am I doing wrong?


texts:
I want to pause  15 seconds then resume without any input when an object is collision other object
this is my code but not working.
Thank you

 void Start(){
    Eifftower = GameObject.FindGameObjectWithTag ("eiffeldespration");
    Eifftower.renderer.enabled = false;
    Time.timeScale = 1;
}

IEnumerator wait() {
    yield return new WaitForSeconds(15f);
    Eifftower.renderer.enabled = false;
    Time.timeScale = 1;
    Debug.Log("test");
}

void OnTriggerEnter2D(Collider2D collisionObject){
            //remove the game object
            if (collisionObject.tag == "Franch" ) {
            Eifftower.renderer.enabled = true;
            Time.timeScale = 1;
            StartCoroutine(test1());
            }
    }


texts: Lightweight NON-dynamic particles in Unity

texts:
I know Unity has an advanced system for managing complex dynamic particle systems with a few thousand elements (Shuriken).

Does Unity have a more lightweight way to create a very, very large (several million in scene) particle system that's basically a vast point cloud of camera-facing billboards that gets created, then just sits in the scene (recalculating normals as necessary in a non-blocking manner as the camera moves around, but otherwise doing nothing) until it gets destroyed and replaced in its entirety a minute later?

The specific application I have in mind is displaying weather radar. Weather radar consists of multiple 360-degree sweeps, each at different inclinations. The collection of sweeps taken in a single round is called a Volume Scan. What I'm trying to do is render the volume scan for a radar site in its entirety, in a way that allows someone to move the camera around and look at it from different vantage points, seeing the storm structure in 3D.

The important thing to remember is that the scene rendered by the camera needs to be able to change with an acceptable framerate as the user looks around and moves the camera, but the underlying point cloud being rendered by the particles changes at most  once every 60 seconds. The only thing that could really  be considered "dynamic" might be recalculating the normals for each point as the camera moves around.

Likewise, assuming normal-recalculation for a 4 million+ particle system wouldn't be instantaneous, I'd at least hope it could be done in a non-blocking manner (I'd rather get 60fps with most of the particles facing in the wrong direction at any instant, then have them gradually snap to face the camera once it stops moving, than have the world completely grind to a halt while Unity recalculates the normals).

I'm pretty sure that raw OpenGL and OpenGL ES can do this with acceptable performance, but I'm trying to stick to Unity for the sake of keeping my app somewhat portable (initially targeting "normal Android" for the sake of having something I can actually make money with immediately, but eventually extending it to support Android VR, Oculus, Magic Leap, HoloLens, etc... if only for the sake of having portfolio projects to show off).

So... does Unity have anything like this? At this moment, I don't necessarily need step-by-step directions... more like some suggestions about what to even SEARCH for, or where to look for documentation about it, since pretty much EVERYTHING particle-related I've found for Unity so far seems to be totally 100% Shuriken-focused.


texts: OpenGL - How can I make the edges of this textured circle smoother?

texts:
I'm building a game and I've applied a certain texture (RAW file) to a circle (GL_POLYGON) in OpenGL. It loads correctly, with the right size and all, but the edges seem a bit jagged and I would prefer them smooth (without any evidence of a polygon being underneath).

GLuint loadTex(int wrap){
GLuint texture;
int width, height;
BYTE * data;
FILE * file;

file = fopen( "tex.raw", "rb" );
if (file == NULL){
    std::cerr << "O ficheiro da textura não foi encontrado" << std::endl;
    return 0;
}

width = 128;
height = 128;
data = (BYTE*)malloc( width * height * 3 );//Alocação do buffer

fread( data, width * height * 3, 1, file );//Ler dados da textura
fclose( file );

glGenTextures( 1, &texture );//Nome da textura
glBindTexture( GL_TEXTURE_2D, texture );//Selecção da textura actual
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );//Parâmetros da Textura
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap ? GL_REPEAT : GL_CLAMP );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data );

free(data);

return texture;
}

void drawCircle(float cx, float cy, float r, float aspectRatio){

GLuint t = loadTex(1);
float angle, radian, x, y, tx, ty, xcos, ysin;

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, t);

glBegin(GL_POLYGON);

for (angle=0.0; angle<360.0; angle+=2.0){
    radian = angle * (M_PI/180.0f);

    xcos = (float)cos(radian);
    ysin = (float)sin(radian);
    x = xcos * r  + cx;
    y = ysin * r*aspectRatio + cy;
    tx = xcos * 0.5 + 0.5;
    ty = ysin * 0.5 + 0.5;

    glTexCoord2f(tx, ty);
    glVertex2f(x, y);
}

glEnd();
glDisable(GL_TEXTURE_2D);
}

Is this a problem from my texture file? Or is it from my code? I apply Line Smoothing before drawing anything (and it is being applied correctly in my lines I believe)


texts: Retrieving text from a text file and inputting it to a Text component

texts:
I had a suspicion I would come across this problem. I know how to write to the file and read from it, but the following snippet isn't allowing me to input it into a text component.

public class EventHandler : MonoBehaviour
{
    string _text;
    Text text;
    private void Awake()
    {
        text = FindObjectOfType<Text>();
    }
    public string Read(string path)
    {
        _text = "";
        StreamReader reader = new StreamReader(path);
        while (!reader.EndOfStream)
        {
            _text += reader.ReadLine();
        }
        reader.Close();
        return _text;
    }
    public void chapter_one()
    {
        text.text = Read("Assets/Chapters/chapter_one.txt");
    }
}

I'm sure you guys can explain why this isn't working. I already got the reference to the Text component as well.

Edit

No errors, file exists, its filled, color is white on black background, chapter_one is the file name and yes chapter_one is called, and I put Debug.Log right in the while loop and out_side of it and I received those logs. My only thoughts are that the string is not getting returned for god knows what reason, or the text component isn't appending the text.


texts: Techniques for mapping "nodes" and paths between nodes in a world space that extends in three dimensions

texts:
I'm trying to create a travellable map/world.  I want to model able-to-be-occupied nodes/tiles/locations and allowed paths between them to create a space infinitely able to be built upon in all directions (not just flatland), in a browser-based game ( http://ninjawars.net , for a sense of it).

For example your character will be in a node "a field", and could then move north into "the first floor of a shack", or south or east or west.   After moving north, movement choices would then be: south back to the field, or up to the second floor of the shack.

Basically, a grid maze with the minor complexity of the up and down option.

What are useful methods for modeling both the inhabitable nodes and the paths between them?  X,y,z euclidean coordinates and relational lists of available connections from individual nodes?

Or are there alternatives to grids that could still allow fun visual representation of movement options?


texts: Dynamically Generated Mesh Not Visible Unless In Wireframe Mode

texts:
I'm trying to create a dynamic mesh using ArrayMesh but my mesh isn't visible unless I turn on wireframe debug mode.
Here is a minimal example of a plane mesh consisting of 2 triangles (this script is currently placed on a Spatial node):
func _ready():
    # With these two lines added I can see the wireframe of the mesh (picture below) otherwise I see nothing.
    VisualServer.set_debug_generate_wireframes(true)
    get_viewport().set_debug_draw(Viewport.DEBUG_DRAW_WIREFRAME)

    var ve : PoolVector3Array = PoolVector3Array()
    ve.push_back(Vector3(0, 0, 0))
    ve.push_back(Vector3(10, 0, 0))
    ve.push_back(Vector3(0, 0, 10))
    ve.push_back(Vector3(10, 0, 10))

    var uv: PoolVector2Array = PoolVector2Array()
    uv.push_back(Vector2(0, 0))
    uv.push_back(Vector2(1, 0))
    uv.push_back(Vector2(0, 1))
    uv.push_back(Vector2(1, 1))

    var co : PoolColorArray = PoolColorArray()
    co.push_back(Color(1, 1, 1))
    co.push_back(Color(1, 1, 1))
    co.push_back(Color(1, 1, 1))
    co.push_back(Color(1, 1, 1))

    var id: PoolIntArray = PoolIntArray()
    id.push_back(0)
    id.push_back(2)
    id.push_back(1)
    id.push_back(1)
    id.push_back(2)
    id.push_back(3)

    var no: PoolVector3Array = PoolVector3Array()
    no.push_back(Vector3(0, 1, 0))
    no.push_back(Vector3(0, 1, 0))
    no.push_back(Vector3(0, 1, 0))
    no.push_back(Vector3(0, 1, 0))

    var array_mesh = ArrayMesh.new()
    var arrays = []
    arrays.resize(ArrayMesh.ARRAY_MAX)
    arrays[ArrayMesh.ARRAY_VERTEX] = ve
    arrays[ArrayMesh.ARRAY_COLOR] = co
    arrays[ArrayMesh.ARRAY_INDEX] = id
    arrays[ArrayMesh.ARRAY_NORMAL] = no
    arrays[ArrayMesh.ARRAY_TEX_UV] = uv

    var m_i = MeshInstance.new()
    array_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
    m_i.mesh = array_mesh
    add_child(m_i)

Now with wireframe debug mode on I see the following:

Otherwise, I can't see anything. If I add an albedo_color to the material_override then the lines will change to be that color. I'm pretty new into procedural generation but I've found that a similar thing will work in Unity so I'm not sure what I'm missing here.


texts:
How can I make a GameObject attach (or "stick") to another GameObject after collision? The problem: I want the GameObject to attach after collision even if it changes scale.

What I have tried:

protected Transform stuckTo = null;
protected Vector3 offset = Vector3.zero;

public void LateUpdate()
{
    if (stuckTo != null)
        transform.position = stuckTo.position - offset;
}

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;

    if(stuckTo == null
       || stuckTo != col.gameObject.transform)
        offset = col.gameObject.transform.position - transform.position;

    stuckTo = col.gameObject.transform;
}

This code makes a GameObject attach perfectly after collision. But when that GameObject changes scale (while it's attached), it visually no longer looks attached to whatever it collided with. Basically, this code makes the GameObject stick with only the original scale at the moment of the collision. How can I make the GameObject always stick to whatever it collided with? And with whatever scale it has during the process?


texts: Rotate heading relative to agent's local space

texts:
I'm having a little trouble translating a point in my game's world space to an object's local space.

I have a cannon in my game with a normalized heading vector that's always supposed to point in the direction of a target. The target is set by an incoming screen touch event.

My problem is that the coordinates I get from the incoming touch events are relative to the game world's axis centered at the world's origin, not relative to the cannon's position like I need. The angle I calculate to rotate the heading is relative to the world's X-axis, not the cannon's local X-axis, this means I can never rotate the heading by anything outside of 0 < x < 90.

I hope my crude drawing conveys what I mean. In the picture below, A is the cannon's position (with the blue heading vector), and B is the target's location (set by an event). The green line represents the angle the game is giving me, and the angle between red line and the heading is what I need to find (the little curved blue arrow).

Here's the code I use to calculate the heading:

 float xDistance = target.x - position.x;
    float yDistance = target.y - position.y;
    float angleToTurn = (float) Math.atan2(yDistance, xDistance);

    vec2RotateAroundOrigin(heading, angleToTurn);

Thanks in advance. Any help is greatly appreciated.


texts: Is it possible to embed a chatbot AI in a game?

texts: Is it possible to embed the AI used in evie cleverbot into a game? For example GTA5 or Sims, to enabe conversations and mood that is if you type something and the game characters will react to what you said and respond back. Is it possible to do this?


texts: Explaining vector math for a pendulum camera

texts:
I came across a code that I guess is doing a pendulum camera, that's the class name. I would like to know the math behind that.  I would like also to know how to decipher those stuff in game math, what are your recommendations ? I already own the book 3D Math for computer graphics by lengyel, but those stuff are not explained there.

        Vector3 r = transform.right;
        Vector3 u = transform.up;
        Vector3 v = transform.forward;

        Vector3 dir = v + u * Mathf.Sin(Time.deltaTime * 0.01f)  + r * Mathf.Sin(Time.deltaTime *0.01f + 0.1f) * -0.1f;
        dir.Normalize();

        Quaternion rotation = Quaternion.identity;
        rotation.SetLookRotation(dir, Vector3.up);
        transform.rotation = rotation;


texts: Can I directly pass a Boost ptr_vector list to glBufferData?

texts:
I have a data structure like this:

typedef struct vertex_ {
float x;
float y;
float z;
float s;
float t;
}vertex;

Then I add to a list called: boost::ptr_vector<vector> vertices;

Is there a way to use vertices to provide the parameters for glBufferData?


texts: How to load up many images without using too much memory

texts: When writing games, I am aware that images take up a lot of space. If one has a large graphical game, they don't want problems with memory, or to give players the message "Go buy a better computer to run this game". However, loading up images everytime one needs an image and discarding it is very slow. So if a programmer has a large graphical game, how can they draw many images without sacrificing performance/memory?


texts: Will an optional device type specific permission hide my game in the Play Store for those types of devices?

texts:
I have heard in many places that if my app uses a permission not applicable to a certain device, it will not show up in the play store for that device. Now, in my code, I am playing audio. I mute that audio whenever there is a phone call by doing this:

 private PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_RINGING) {
                    onPhoneCallInterrupt(); //Method I made that mutes audio for phone call
                } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                    onPhoneCallInterrupt(); //Method I made that mutes audio for phone call
                }
        }
    };

Now, this uses the following permission in the manifest:

<uses-feature android:name="android.permission.READ_PHONE_STATE"  android:required="false" />

Will I get any exceptions because I have made the permission optional by doing android:required = "false" on devices that don't have phone compatibility (tablets)?

The reason I am so confused on this, is because I am checking if the phone is being used, but I am not using it. So, will my app work on tablets, let alone show up in the play store for them?

Thanks for helping me clear up this confusion,

Ruchir


texts: Material becomes undefined when I create a prefab in Unity

texts:
I have a parent GameObject and nested models in it. When I create a prefab, I lose contact with the material in some parts of the model. Why is this happening? And how to avoid this?

Object Hierarchy:

The settings themselves:

prefab on scenes:


texts: Any possibility to render XNA scene via POV-Ray

texts:
We are creating special purpose application. Its not game but its 3d Application that functions like game. We require app to have different places and we want to allow user to roam inside such places and take photographs of views.

Here is what we are doing

We are creating a model of a place (e.g. Room Interior) in 3Ds Max
We are exporting FBX file
We are importing FBX file in XNA. Adding lights , placing camera.
Application lets user rotate and move camera in any direction. Just as if you are moving character in FPS game.

Goal:

We want to capture high quality screenshot from the camera view point. We require hyper-realistic looking image.

What we do :

To achieve this we are capturing screenshot by storing screen pixels in an Image.

Problem :

Its pathetic quality image. As it is just a frame of run-time 3d render.

======

A. I heard POV ray is programmable renderer that can be helpful . But I dont know how will it fit in our current setup.

B. Is there any other approach which I can take to render high quality by looking at our current setup.

C: If I wish to entirely start from scratch , how should I code this application.

NOTE : I am just product manager for this app. I am not actual developer. But I have been web developer myself. I never did 3D programming though. But I know basics of all these.


texts: How do I show the current view from the viewport on my map?

texts:
I'm doing HTML5 Canvas development and currently have a large viewport (on the left) and a map (on the right). Like this:

I need to show on the map what is currently being viewed in the left. And I'm at a lost on how to calculate this. This is how I want it to be:

I am manipulating the main viewport via a transformation matrix. like [1, 0, 0, 1, 0, 0]

This is decently common functionality in different games and apps. So I assume there are resources on how to do it. But I haven't been able to find any.


texts: Level design: compute minimum time between two items for player traversal

texts: Do any game toolsets offer a means of computing the minimum time it would take a player to move between two objects (or positions, more generally) in a level? I'm not asking about how one would go about calculating this, but rather just whether or not it has been done, and if so, examples.


texts: How to make pathfinding agents avoid each other using A* in unity?

texts:
So far Ive implemented a 2D grid graph using 2D physics. My enemies have a seeker script, AI destination setter (with the player position attached) and a basic AIPath script that is set to 2D
When I press play, my enemy game objects move away from the marked area where they can't go, and the area remains static. Is there a way to make this marked area follow the colliders using A*?
This is the script Im using: https://arongranberg.com/astar/documentation/4_1_16_7f164ebc/aipath.html
I don't have the pro version of the above asset though, so can't make use the built in function that handles situation like this.