texts: Can games be made with Win32 for Windows 10?

texts:
Based on the news today of Microsoft allowing Win32 games on the Windows store, what does it mean that Win32 can be used for games now?  Couldn't Windows 10 already play Win32 games?  or is this solely for distribution over the Window Store
that is important?

Couldn't Windows 10 already play Win32 games?  What were developers using if it wasn't Win32 on Windows 10 (UWP?)

Quoted in many articles, but here is the original,

https://news.xbox.com/en-us/2019/05/30/microsoft-approach-to-pc-gaming/


texts: How to start an animation just once on an event in libGDX

texts:
I am trying to show an explosion animation which i created using a few textureregions and created Animation missileblastAnimation from those textureregion like this -- >

 TextureRegion[] explosion = { explodemissile1, explodemissile2, explodemissile3, explodemissile4, explodemissile5,
                 explodemissile6, explodemissile7,explodemissile8, explodemissile9, explodemissile10, explodemissile11,
                 explodemissile12, explodemissile13, explodemissile14,explodemissile15, explodemissile16, explodemissile17,
                 explodemissile18};
        missileblastAnimation = new Animation(0.1f, explosion);
        missileblastAnimation.setPlayMode(Animation.NORMAL);

I have this following code in the render method -- >
Note:-  explosionstarted is set to true when missile hits the ground

  if(explosionstarted){//check if the missile hits the ground to start explosion animation
       batcher.draw(AssetLoader.missileblastAnimation.getKeyFrame(runTime),
                              100, 300-102, 50, 102);
      if(AssetLoader.missileblastAnimation.isAnimationFinished(runTime)){
     // i found that isAnimationFinished tells if animation is finished or not but i still cant understand the passing runTime thing
          explosionstarted = false; //reset the boolean to make the animation stop drawing
        }
    }

Problem is the animation is not playing as it should i.e sometimes it plays too much fast . sometimes it skips first few frames and jumps to ending frames.
What is the right way to do this?
Is there any other way i can check if the animation is completed ?


texts: Even if one client port will be simple to write without it, should I still use an engine?

texts:
So the idea is to create a TRUE REAL TIME strategy game that is working as android and IOS app, and also as  web browser game. Players should be able to play on all their devices.

There will not be any physics but there will be alot of data transfering, many diferent calculations, settings. There will not be client to client direct connection, everything should go trough servers. Graphics will be simple Menus/ different pictures. Player interactions will not be graphically presented. More like raw data.

Friend's chat, team chat, Maybe global chat. Facebook/Google connection/authorization. Notifications... etc

Now after I explained the idea here are the question:

Given that the browser client will be relatively simple to write without an engine (using javascript/html/sql), should I still use a game engine to write the different clients (browser, iOS, Android); if I can avoid using an engine for one port, should I avoid using an engine at all? And, more importantly, why?


texts: HTML Canvas Makes Everything Bolder On Right Side

texts:
For some strange and sudden reason, my canvas seems to make lines thicker and darker on the right ~1/4-ish. I have tried multiple browsers and different computers and they all have the same rendering issue EXCEPT for Chrome for Android. Here is a screenshot of the test lines that I drew:

And here is the code in case anyone was wondering:

var canvas = document.getElementById("foreground");
var context = canvas.getContext("2d");
var height = 450;
var width = 600;

canvas.width = width;
canvas.height = height;

function draw() {
  context.clearRect(0, 0, canvas.height, canvas.width);

  for (var i = 1; i < (800 - (0 * 2)) / 35; i++) {
    context.beginPath();
    context.moveTo(200 + (i * 35) + 0 | 0, 50 + 0 | 0);
    context.lineWidth = 1;
    context.lineTo(200 + (i * 35) + 0 | 0, 50 + 800 - 0 | 0);
    context.strokeStyle = "black";
    context.stroke();
    context.closePath();
  }

  for (var i = 1; i < (800 - (0 * 2)) / 35; i++) {
    context.beginPath();
    context.moveTo(200 + 0 | 0, 50 + (i * 35) + 0 | 0);
    context.lineWidth = 0.5;
    context.lineTo(200 + 800 - 0 | 0, 50 + (i * 35) + 0 | 0);
    context.strokeStyle = "black";
    context.stroke();
    context.closePath();
  }

  requestAnimationFrame(draw);
}

draw();
<div id="container">
  <canvas id="foreground"></canvas>
</div>


texts:
First off, I'm asking this question here because gaming and messaging are intimately connected.  Why win if you can't gloat?  Nevertheless, I won't be offended if this needs to be moved to overflow.

I need a PM system for my browser game, which already has a user and authentication system (To clarify: the game already has a user system).  Specifically, I'm wondering if a PHP library already exists that I can use to save some time.  Better yet, if anyone knows of a nice Codeigniter library for messaging, that would be perfect.

I already have a good idea on how I would approach this if I have to write my own, but it seems like something that would already exist in a robust form (despite my failed Google searches).

Requirements:

Messages can be sent to individuals,  multiple users, and guild mates (which is essentially just multiple users with server-side selecting who to target).
Users can reply to individual or all recipients
Messages appear in sender's outbox and receiver's inbox.
Utilizes some 2-table design to handle marking read / deleting messages on a user-by-user basis
Messages are semi-threaded.  I.e. I won't necessarily have them appear in the GUI as threaded, but previous messages should be included at the bottom of a reply.  Maybe better to say, previous messages are identifiable and accessible.  (This, I'm not yet 100% sure how I would design if I write my own.  I.E. whether to include the text of the previous message into the new message or somehow remember the previous message's database ID to link later)

Technology in Use: PHP, Codeigniter, Javascript, JQuery, Ajax, Sqlite

Note:
I have seen that there are some similar questions on overflow, but they were very little help in the answer department. Otherwise, people were looking for either chat boxes or more umm.. like social media site threads, which I find a bit different than something you would find in a game.


texts: GLSL uniform array with size set by another uniform

texts:
Will the follwing GLSL code work?

#version 330

uniform int size;
uniform float[size];

void main() {
  //do something
}


texts: Is it possible to trigger a loop with key input

texts:
Ok I need to know if it is possible to trigger a gameloop with a key press?
ex code

 if (GamePad.GetState(PlayerIndex.One).Buttons.X == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            ball.Update();
        }

obviously this is wrong because when I press the up button the ballstarts moving but stops when I release. and yes I looked online and couldn't find anything on this


texts: How can I implement audio stop/pause/resume in Java?

texts:
In Java, we can play audio like this:

audioInputStream = AudioSystem.getAudioInputStream(audio);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
sourceDataLine.open();
sourceDataLine.start();
floatVoiceControl.setValue(-20);
byte[] buf = new byte[0xFF];
int onceReadDataSize = 0;

// look at here
while ((onceReadDataSize = audioInputStream
     .read(buf, 0, buf.length)) != -1)
  sourceDataLine.write(buf, 0, onceReadDataSize);

Seems that we can play audio by doing some initializations and create a loop that continuously do sourceDataLine.write.
So, I think I can implement pause/resume by changing the last few lines to:

// look at here
while (true) {
  if (!paused)sourceDataLine.write(buf, 0, onceReadDataSize);
  onceReadDataSize = audioInputStream.read(buf, 0, buf.length);
  if (onceReadDataSize == -1) break;
}

But it doesn't work -- it just stop when I set paused to true in another thread, and when I set it back to false, it doesn't resume.

Is there any workarounds? Or is there any alternative Java audio library?


texts:
I am trying to render some entities in random positions on the screen. The spawning positions are okay however when I move the player entity (which the camera is focused on) and pass the middle of the screen (then the camera starts moving) the sprites of the other entities also move with me, which I do not want.

I tried giving them postions in the world and not in the screen using cam.unproject(position); which converts psotions relative to the screen into positions relative to the game world, but that did not work either.

They are rendered the same way all other sprites are rendered in libgdx

This is the code where I initialize the entities:

Texture zombie = new Texture("zombie.png");
    float x, y;
    for (int i = 0; i < enemy_amout; i++) {
        x = rm.nextFloat() * (mapWidth * 8f- zombie.getWidth());
        y = rm.nextFloat() * (mapHeight * 8f - zombie.getHeight());
        Vector3 position = new Vector3(x, y, 0);
        cam.unproject(position);
        enemies[i] = new Entity(zombie, position.x, position.y, 1);
    }

This is what the game looks like when I start it

And this is what it looks like after I moved the player character to the right. As you can see they moved alongside the camera but I want them to remain on their original positions.


texts:
I have a RawImage and an AspectRatioFitter attached to it so I want to change the aspect ratio to fit the image in the texture field of the raw image.
But I need to avoid checking for it in the update as much as possible.
Is there an event for when the texture of a RawImage element has changed? Something like OnTextureChanged().


texts:
I am looking for detect touch in an actor. The touch in my game is detected in wrong part of the screen. I want to detect touch only on the red circle, here is the code:

Static_values

public class Static_values {

    static public float Width = Gdx.graphics.getWidth();
    static public float Height = Gdx.graphics.getHeight();

}

Circle class:

public class Circle_Obj extends Actor{

    private Vector2 position;
    private float radius;

    private float speedX;
    private float speedY;

    private com.badlogic.gdx.math.Circle circle;
private Texture texture;

    public Circle_Obj(float x, float y, float radius) {

        position = new Vector2(x,y);
        this.radius = radius;

        speedX = 5.5f;
        speedY = 5.5f;

        circle = new com.badlogic.gdx.math.Circle(x,y,radius);
        texture = new Texture(Gdx.files.internal("texture.png"));

        this.setSize(Static_values.Width,Static_values.Height);
        this.setPosition(position.x,position.y);
        this.addListener(new InputListener(){
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log("TOUCHED", " TOUCHED ");
                return true;
            }
        });

    }

    @Override
    public void draw(Batch batch, float parentAlpha) {

        this.setSize(Static_values.Width,Static_values.Height);
        this.setPosition(position.x,position.y);
        batch.draw(texture, position.x, position.y, radius, radius);
}

Screen class :

public class GameScreen implements Screen {

    private Stage stage;
    private Circle_Obj circle_obj;

    public GameScreen() {

        circle_obj = new Circle_Obj(Static_values.Width/3, Static_values.Height/3, Static_values.Width / 100 * 10);

        stage = new Stage();
        stage.addActor(circle_obj);

        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.draw();

    }
/** other methods **/

Colored area = area where touch is detected :


texts: How to make a sprite face the player sprite (pygame 2d)

texts:
Basically I have a sprite and I want its front/face to face the player sprite. All the sprites are rectangles/squares and use .get_rect().
I have a base class for the sprite here:
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super(Enemy, self).__init__()
        self.surf = pygame.Surface((20, 10))
        self.surf.fill((255, 255, 255))
        self.rect = self.surf.get_rect(
            center=(
                random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
                random.randint(0, SCREEN_HEIGHT),
            )
        )
        self.speed = random.randint(15,30)

    # Move the sprite based on speed
    # Remove the sprite when it passes the left edge of the screen
    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()

And the class for the player:
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.surf = pygame.Surface((40, 25))
        self.surf.fill((255, 255, 255))
        self.rect = self.surf.get_rect()
    def update(self, pressed_keys):
        if pressed_keys[K_UP] or pressed_keys[K_w]:
            self.rect.move_ip(0, -10)
        if pressed_keys[K_DOWN] or pressed_keys[K_s]:
            self.rect.move_ip(-0, 10)
        if pressed_keys[K_LEFT] or pressed_keys[K_a]:
            self.rect.move_ip(-10, 0)
        if pressed_keys[K_RIGHT] or pressed_keys[K_d]:
            self.rect.move_ip(10, -0)
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= SCREEN_HEIGHT:
            self.rect.bottom = SCREEN_HEIGHT


texts: Component-Entity Systems Code Generation

texts:
I'm really enjoying component entity approach (I'm currently using ASH haxe, but particular language/framework doesn't really matter).

However the problem is - there're way too many elementary classes that need frequent update.

So I'd like to have something like yml config file for components and nodes, and actual classes to be generated from it. Is there any already existing solution that utilizes such codegen, or maybe some generic codegen solution that should be easy to configure for such task?


texts: 2D RPG - Character sprite size bigger than tile size

texts:
Ok so I'm trying to make a nice little RPG game in Java & Slick2D engine, the tiles are 16x16, so the collision array is also 16x16, how ever my character sprite is 16x20

What would be the best method of moving the character in relation to a 16x16 grid, also checking for collision?


texts:
I've been developing single player games for a while now and I have decided to start working on a online PC(and maybe mobile) TCG. The design is almost complete and I can cover most of the code as far as single player goes.

My question is:

Do I have to implement some sort of server-client model in order to make it possible for two player to get in a match together?


texts: How to make a collider the follows all the animations of a prefab?

texts: I have attached a capsule collider with my player(prefab) and made a script so that when Space key is down it does the jump animation in Unity. But because of the collider not jumping with the player, the player gets stopped by obstacles though he visually passed it. How can I make a collider that moves with my animations attached to a prefab?


texts: How to output to the Oculus and a 2D screen?

texts:
We'd like to present an Oculus game to a large group of people. Not everyone will have an Oculus headset, so we'd like to output to both the Oculus and a second display. The problem is that the project uses an Oculus plugin to render its output, so all they output is two distorted circles, which doesn't display well when not wearing the Oculus headset.

I thought of making a second Unity client (the "audience" client, running on the same computer as the Oculus application) that receives the output texture of an "audience" camera from the client running the Oculus version.

My question is: Can I use the network to send the output of a camera to the "audience" client so I can set it up for the second display, bypassing the Oculus plugin? How would I get the input on the "audience" client to map it to the screen?


texts: How to change the Art of the Catch script in order to spawn random items?

texts:
I've downloaded the mod Art of the Catch and I was wondering how I could change the scripts in order to spawn three new category of items:

any ingredient (dragon bones)
any non-enchanted craftable item (iron helmet)
any enchanted craftable item (ring with magic enchantment that is vanilla or added by a mod)

Looking at the source code, I found this:

function SelectFish()
    Form fish_base = fish_detected.GetBaseObject()

    if fish_base == CritterPondFish01
        PlayerRef.AddItem(CritterPondFish01Ingredient, 1, true)
        _AC_CaughtFish01.Show()
    elseif fish_base == CritterPondFish02
        PlayerRef.AddItem(CritterPondFish02Ingredient, 1, true)
        _AC_CaughtFish02.Show()
    elseif fish_base == CritterPondFish03
        PlayerRef.AddItem(CritterPondFish03Ingredient, 1, true)
        _AC_CaughtFish03.Show()
    elseif fish_base == CritterPondFish04
        PlayerRef.AddItem(CritterPondFish04Ingredient, 1, true)
        _AC_CaughtFish04.Show()
    elseif fish_base == CritterPondFish05
        PlayerRef.AddItem(CritterPondFish05Ingredient, 1, true)
        _AC_CaughtFish05.Show()
    elseif fish_base == CritterSalmon01 || fish_base == CritterSalmon02 || _AC_FishWaterfallTypes.HasForm(fish_base)
        PlayerRef.AddItem(FoodSalmon, 1, true)
        _AC_CaughtFishSalmon.Show()
    endif
endFunction

It was inside _ac_beginfishing.psc with other functions. I am pretty sure I just need to modify the function, but I am not sure if we can use a general class of items as a variable, and I am even less sure about adding items with enchantments, because from what I know there's no variable that points to a list of items.

Anyway, how would you change the scripts so that it spawns random items? The way I would do is generate a random number and use it to select an item in a list, but I am not familiar with the scripting language, so I am not exactly sure how I could do that or even if it's possible.


texts: Calculating gameObjects hit by a directional light source

texts:
I am trying to figure out in my current game whether a gameObject is lit by a directional light or not. Below is my image inside the Unity game engine

As my game runs around a Day/Night cycle, I need to constantly check which hex tiles are lit and which are not. I am using one directional light source in my scene and I am rotating it around the x-axis for the day night cycle.

Currently, I am using the dot product to calculate if the tile is lit by the directional light but its not very accurate.

 Vector3 forward = Light.transform.TransformDirection(Vector3.forward);
 float dot = Vector3.Dot(forward, -(tile.transform.position - Light.transform.position));

Is there a better way to do check this inside Unity??


texts:
Both of these balls are the same scale (1) but one is a lot bigger.

What can cause this? I don't think I've ever scaled the ball anywhere in my code.


texts: if the player moves in the real world the game object also want to move

texts:
I am creating an iOS game. It's my first experience in iOS. I am facing an issue in player movement. If the player moves in the real world this means the game object (character in the game) also wants to move. So I tried to access pedometer to take the step count. But it is not updating. It's showing the step count as 0 only. The value is not changing. Here's my script:

 private float loLim = 0.005F;
 private float hiLim = 0.3F;
 private int steps = 0;
 private bool stateH = false;
 private float fHigh = 8.0F;
 private float curAcc= 0F;
 private float fLow = 0.2F;
 private float avgAcc;

 public Text stepCountTxt;

 public void Update(){
   stepDetector();
 }

 public int stepDetector(){
 curAcc = Mathf.Lerp (curAcc, Input.acceleration.magnitude, Time.deltaTime * fHigh);
 avgAcc = Mathf.Lerp (avgAcc, Input.acceleration.magnitude, Time.deltaTime * fLow);
 float delta = curAcc - avgAcc;
     if (!stateH) {
         if (delta > hiLim) {
             stateH = true;
             steps++;
         }
     } else {
         if (delta < loLim) {
             stateH = false;
         }
     }
     avgAcc = curAcc;
     calDistance (steps);

 return steps;
}

void calDistance(int i){
   stepCountTxt.text=i.toString();
}


texts:
I'm making a game like this:
https://www.youtube.com/watch?v=hO7573lphqI

wherein a 3D ship is flying around on a 2D plane.  From the player's perspective, the ship will stay stationary in the center of the screen.

The question I have is whether it's better to have to ship stay stationary and the world move around the ship? Or should I have the camera follow the ship as it moves around?

Notes:

assume the ship can go infinitely in any direction
this is in Unity, though I'm curious if that differs from other tools like Unreal
I will be culling items that are offscreen either way

Obviously, having the camera follow the ship is easier from the programming side of things, but I'm wondering if there's a good reason not to do that (if the player moves far enough in one direction does it hit an internal limit that would break the game)?

Thanks!


texts:
I am looking for 2D game concept sketching software(not engine). Something that will let me put sprites, backgrounds together and maybe do some minimal animations. The ultimate goal is to design game concept, to transfer something from your mind to visual representation with ease. So I can quickly look at those skethes and see if the concept worth something, show to others and then start development.
I work with photoshop, but it is not as productive as special software could be.


texts: Best practices in managing character states

texts:
While in development of a character, I feel like I'm digging myself deeper into a hole every time I add more functionality to him, creating more bugs and it seems like my code is tripping over itself all over the place.

What are the best practices when managing character states for a character that has a large selection of abilities and actions that they can perform, without their abilities interrupting each other and creating a mess overall?


texts: First object jumps on re-entry of second colliding object

texts:
The scenario is that I have two objects - Object A and Object B. The Object A is lying on the ground and when Object B enters the collider of Object A, the Object A moves (only X and Z axis) with Object B. The movement works well with the script shown below.
The issue is that most of the time, the Object A's initially position shifts by few meters whenever Object B enters its collider. I feel it is related to offset position. What should happen is that, Object A should be the same position when Object B enters the collider and move along with Object B only when Object B moves.
So how do I fix this?
private Vector3 offsetPosition;

public Transform ObjectB;

public bool ObjectB_Collision = false;

void Start () {
        offsetPosition = ObjectB.transform.position - this.transform.position;
    }

    void ObjectB_HasEntered() {
        offsetPosition = ObjectB.transform.position - this.transform.position;
    }

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

        if (ObjectB_Collision == true) {
            this.transform.position = new Vector3 (ObjectB.transform.position.x, this.transform.position.y, ObjectB.transform.position.z) - new Vector3 (offsetPosition.x, 0, offsetPosition.z);
        }

    }

public void OnTriggerEnter (Collider col) {
        if (!enabled) return;

        if (col.gameObject.name == "Object_B") {
            ObjectB_HasEntered();
            ObjectB_Collision = true;
        }
    }

public void OnTriggerExit (Collider col) {
        if (!enabled) return;

       if (col.gameObject.name == "Object_B") {
            ObjectB_Collision = false;

        }
    }
```


texts: How to handle large scene/game in unity3d?

texts:
I have a very very Big/Huge scene to load and I can't load it at once.

The one strategy i know is that  I divide the scene into multiple scenes and load my scenes it into async manner as my character controller move. I am moving my character controller and accordingly loading (its near)scenes by matching its position. But it is not smooth. . .

How do I load big scene smoothly? what will be the strategy? Is this right strategy which I am doing or there is any other feasible and easy to use solution available.?


texts:
I've recently started learning how to program in 3D with XNA and I've been trying to implement a Terrain3D class(a very simple height map). I've managed to draw a simple terrain, but I'm getting a weird bug where I can see through the terrain. This bug happens when I'm looking through a hill from the map. Here is a picture of what happens:

I was wondering if this is a common mistake for starters and if any of you ever experienced the same problem and could tell me what I'm doing wrong. If it's not such an obvious problem, here is my Draw method:

public override void Draw()
{
    Parent.Engine.SpriteBatch.Begin(SpriteBlendMode.None,
        SpriteSortMode.Immediate, SaveStateMode.SaveState);

    Camera3D cam = (Camera3D)Parent.Engine.Services.GetService(typeof(Camera3D));
    if (cam == null)
        throw new Exception("Camera3D couldn't be found. Drawing a 3D terrain requires a 3D camera.");

    float triangleCount = indices.Length / 3f;

    basicEffect.Begin();

    basicEffect.World = worldMatrix;
    basicEffect.View = cam.ViewMatrix;
    basicEffect.Projection = cam.ProjectionMatrix;
    basicEffect.VertexColorEnabled = true;

    Parent.Engine.GraphicsDevice.VertexDeclaration = new VertexDeclaration(
        Parent.Engine.GraphicsDevice,
        VertexPositionColor.VertexElements);

    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Begin();
        Parent.Engine.GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0,
            VertexPositionColor.SizeInBytes);
        Parent.Engine.GraphicsDevice.Indices = indexBuffer;
        Parent.Engine.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
            0, 0, vertices.Length, 0, (int)triangleCount);
        pass.End();
    }

    basicEffect.End();

    Parent.Engine.SpriteBatch.End();
}

Parent is just a property holding the screen that the component belongs to. Engine is a property of that parent screen holding the engine that it belongs to.

If I should post more code(like the initialization code), then just leave a comment and I will.


texts: How do I access the pixels of an SDL 2 texture?

texts: How exactly can one get to the RGBA pixel arrays of SDL 2.0 textures? Does the texture need to be specially initialized and locked down?


texts: Unity: how to update only the Windows executable?

texts:
Suppose I made a small changes to the source code of my game. No assets, textures or sounds are changed.

How can I create a "patch" or "update" for the Windows build of my game so my customers don't need to re-download everything?


texts: How can I list files in a folder from JavaScript in cocos2d-x?

texts:
I need to list all the files in the res folder from a JavaScript script in cocos2d-x. What would be the most efficient way to do this?

To keep compatibility with Cocos2d-html5 a JavaScript-only solution is most desirable.


texts: why am I being unable to access public array of a class inside other class?

texts:
I know this question has been asked before but my case is different(or i could not gather any kind of help from those)

I am facing "NullReferenceException: Object reference not set to an instance of an object" Error

in Class 1 I tried to make an array of a Class2 type and that class2 had two arrays of type "int"

but when i am filling up values in those arrays of Class2, by making object of Class2. it seems to be null.

well right now its not a problem but when i will use those value in other place it will create one. so i would really like to solve this right now.

PS:-
At first I used to fill those value by inspector plane in unity.
but now i want to fill them up by programatically at runtime

Class1 Code

public class LevelStructure : MonoBehaviour
{
public static LevelStructure instance;

public int numberOfColumns=5;
public int numberOfRows=5;
internal ColumnStructure[] columnStructures;

int[] tilemap = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] jellymap = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
void Awake()
{
    instance = this;
    //numberOfColumns = transform.GetChildCount();
    //columnStructures = transform.GetComponentsInChildren<ColumnStructure>();

    // I added the below code to put values at runtime programatically.
    // before that i used to put those from unity inspector plane.
    for (int i = 0; i<numberOfColumns; i++)
    {

        ColumnStructure cs = new ColumnStructure();

        for(int j = 0; j<numberOfRows; j++)
        {

            if(cs==null)
            {
                Debug.Log("CS is null");

            }
            else
            {
                Debug.Log("CS is not null "+j);
                cs.itemAvailability[j] = (int)tilemap[i*numberOfColumns+j]; //This line is getting null reference exception
                cs.jelly[j] = (int)jellymap[i*numberOfColumns+j];

            }

        }
        columnStructures[i] = cs;

    }

}

}

Class2 Code :-

public class ColumnStructure
{

public int[] itemAvailability;
public int[] jelly;

}

Console Log :-

CS is not null 0
UnityEngine.Debug:Log(Object)
LevelStructure:Awake() (at Assets/CM3/Scripts/Game Scripts/LevelStructure.cs:35)

NullReferenceException: Object reference not set to an instance of an object
LevelStructure.Awake () (at Assets/CM3/Scripts/Game Scripts/LevelStructure.cs:36)

ANSWER :-

Thanks to Petr Abdulin, I modified Class2 Code like this.

public class ColumnStructure
{

public int[] itemAvailability = {1,1,1,1,1,1,1,1};
public int[] jelly = {1,1,1,1,1,1,1,1};
void Awake()
{

}
}


texts: Detecting mouse click for the uppermost layered 2d sprite in Unity

texts: I have two sprites. One for the entire background and another small sprite, which is a foreground object. I have written code for both of these objects in their OnMouseDown() functions. When I click on the foreground object, theMouseDown()method of background object also gets called since it is behind the foreground.I just want my foreground sprite to react when I click it, not both foreground and background sprites.


texts: Algorithm for randomly generating reachable platforms

texts:
I want to randomly generate reachable platforms on the fly for a 2D game.  Right now, I am just creating platforms at random x,y positions.  Only 4 platforms can exist at once, so once the 5th one is generated the 1st one is removed (fifo).

So, I want to ensure that the player can jump from his current platform to at least one other at any given time.

I was thinking of using some variant of the distance formula to calculate the location of the next platform being generated.  I was hoping someone could help me out with the formula for calculating the next platforms possible x,y positions.

The player variables I am assuming will be important are speedX, speedY, and gravity.

From here, I should be able to calculate the maximum distance to plug into the distance formula.

However, I am thinking that some variation of the distance formula that contains a variable for slope would be better in my case.

I want to ensure that the player will never get stuck on a platform with no where it can jump.  Also, I want to ensure that platforms aren't generated on top of each other.

Formulas/images/code are a huge plus.

Here is how jumping is currently working.

Field speedY:Float = 4
Field GRAVITY:Float = .05

Method Update:Void()
    If KeyDown(KEY_SPACE) And not jumping Then
        dy=-speedY
        jumping = true
    EndIf

    If jumping
        dy += GRAVITY
        local tempY:Float = y + dy
        y = tempy
    Endif
End Method

Edit:
I now understand that the formula is just the displacement of basic projectile motion.

Except, in my case, we don't care about cos/sin because the angle will always be the same.


texts:
I'm following the 2D Roguelike tutorial, which can be seen here. I don't want to get fancy, just follow the existing steps.

I've reached the part where all it's supposed to do is draw the playfield.  But it looks like this:

and I don't know why.

Some of the floor tiles are appearing beyod the outer wall, and others are missing (or maybe they're stacked on top of other tiles).

(EDIT: I discovered that the "missing" tiles are because I had the sprites in the wrong layer, and fixed them. I still have several appearing to the left of the outer wall, though.)

I tried to debug it in Visual Studio. The plan was to step through it line by line to see how the tiles are put down, but the debugger doesn't show the playfield until the whole thing is complete.


texts: Why the points List and the agents List are empty in the WaypointsAI script?

texts:
I created a class for the points and agents :

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

using System.Linq;
using System;
using UnityEngine.AI;

[Serializable]
public class WaypointsClass
{
    public List<Transform> points = new List<Transform>();
    public List<NavMeshAgent> agents = new List<NavMeshAgent>();
}

Then created a script that find waypoints and add them to the points list and agent/s to the agents list:

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

public class RedWaypoints : MonoBehaviour
{
    public GameObject[] redWaypoints;
    public NavMeshAgent redAgent;

    private void Awake()
    {
        redWaypoints = GameObject.FindGameObjectsWithTag("Red_Waypoint");

        WaypointsClass wpc = new WaypointsClass();

        foreach (GameObject point in redWaypoints)
        {
            wpc.points.Add(point.transform);
        }

        wpc.agents.Add(redAgent);
    }

    // Start is called before the first frame update
    void Start()
    {

    }

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

    }
}

In the end the WaypointsAI script :

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

public class WaypointsAI : MonoBehaviour
{
    public WaypointsClass waypoints;
    public float distanceToContinue;

    private float currentDistanceToPoint;
    private int lastPointIndex;
    private int goalPointIndex;

    void Start()
    {
        //Firstly check if the waypoints are set up correctly
        if (waypoints.points.Count < 1)
        {
            Debug.LogError("Set up the waypoints for this gameObject!");
        }
        else
        {
            //Now set up the path
            lastPointIndex = 0; //Start from the index 0
            waypoints.agents[0].transform.position = waypoints.points[0].position;
            if (waypoints.points.Count > 1)
            {
                goalPointIndex = 1; //Go to the [1] waypoint
            }
            else
            {
                goalPointIndex = 0;
            }
        }
    }

    void FixedUpdate()
    {
        for (int i = 0; i < waypoints.agents.Count; i++)
        {
            //Calculate the distance and check if it should move to the next waypoint.
            currentDistanceToPoint = Vector3.Distance(waypoints.agents[i].transform.position, waypoints.points[goalPointIndex].position);
            if (currentDistanceToPoint <= distanceToContinue)
            {
                //Save the old index, totally useless in this implementation though
                lastPointIndex = goalPointIndex;
                //Increase goal index to change the goal waypoint to the next, (Or maybe random one?)
                goalPointIndex++;
                if (goalPointIndex >= waypoints.points.Count)
                    goalPointIndex = 0;
            }

            //Now move towards the current waypoint, Change this to fit your code with navMesh anyway I think I did a lot for you anyway
            waypoints.agents[i].transform.LookAt(waypoints.points[goalPointIndex].position);
            waypoints.agents[i].transform.Translate(Vector3.forward * Time.deltaTime * 10);
        }
    }
}

The problem is that in the first line in the WaypointsAI script the points List is empty :

if (waypoints.points.Count < 1)

points is empty. How can I resolve it ?


texts: fading from one scene to another not working

texts:
I am using the following code to fade from one scene to another, but it doesn't fade. It just loads the next scene without fading. I suspect there's something wrong with the image I'm using. I used a black .png image with dimensions 425×344 that I downloaded from Google. How can I solve this issue?

Fading.cs (I added this to an empty game object)

public Texture2D fadeOutTexture;
public float fadeSpeed = 0.8f;

private int drawDepth = -1000;
private float alpha = 1.0f;
private int fadeDir = -1;

void onGUI () {

    alpha += fadeDir * fadeSpeed * Time.deltaTime;
    alpha = Mathf.Clamp01(alpha);
    GUI.color = new Color (GUI.color.g, GUI.color.b, alpha);
    GUI.depth = drawDepth;
    GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture); }

public float BeginFade (int direction) {
    fadeDir = direction;
    return (fadeSpeed); }

void onLevelWasLoaded() {
    BeginFade (-1);

}

In the script of the trigger object:

IEnumerator gameScene2() {
    float fadeTime = GameObject.Find ("FadeObject").GetComponent<Fading>().BeginFade(1);
    yield return new WaitForSeconds(fadeTime);
    Application.LoadLevel("Scene2");
}

These are the image settings for the black .png image


texts: How do I prevent memory-modification cheats?

texts:
There are many memory-altering programs out there nowadays (Cheat Engine & co).  Is there an efficient way to keep a constant variable actually constant?

I had two ideas:

Make a separate thread updating the constant variable to a constant value, e.g. 200 every minute. Problem: One can also alter the second value.
Store the value on the server. Problem: I want to keep the network traffic as low as possible.

I need this mechanism for both constants and variables only allowed to contain a certain range of values.

Are there better ways to do this?


texts:
I have come across a problem in my code for my game. Currently i am developing a 2D platformer game in pygame. I have gotten the character to move left and right, although i haven't been able to get him to jump. I have experimented with a number of possibilities that all haven't worked.

while True:
    #handles user input
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT or event.key == K_a) and player.direction != RIGHT:  #if the left key is pressed
                player.direction = LEFT  #change the direction to left
                player.playerPicture = player.runLeft
                player.playerPicture = player.playerPicture.convert_alpha()
                DISPLAYSURF.blit(player.playerPicture, (player.playerx, player.playery))

            elif (event.key == K_RIGHT or event.key == K_d) and player.direction != LEFT:  #if the right key is pressed
                player.direction = RIGHT #change the directions to right
                player.playerPicture = player.runRight
                player.playerPicture = player.playerPicture.convert_alpha()
                DISPLAYSURF.blit(player.playerPicture, (player.playerx, player.playery))

            elif (event.key == K_UP or event.key == K_w) and player.direction != LEFT and player.direction != RIGHT:
                player.direction = UP
                player.playerPicture = player.jump
                player.playerPicture = player.playerPicture.convert_alpha()
                DISPLAYSURF.blit(player.playerPicture, (player.playerx, player.playery))

            elif event.key == K_ESCAPE: #if the escape key is pressed
                 terminate()  #quit the game

        else:
            player.playerPicture = player.standingStill
            player.playerPicture = player.playerPicture.convert_alpha()
            player.direction = None

    DISPLAYSURF.fill(Black)

    #update game state

    if player.direction == LEFT:
         #if the players position is greater than the left boundary
        if (player.playerx > boundaryLeft):
            player.playerx -= 8 #move the player to the left

        #if the direction is right
    elif player.direction == RIGHT:
        if (player.playerx < boundaryRight): #player is less than the right boundary
            player.playerx += 8  #move the player to the right

    elif player.direction == UP:

This code is in the mainloop of the game. It pretty much checks what key has been pressed, applies the appropriate image for the character and changes the direction. Afterwards the character is manipulated based on the direction that he is facing. If he is facing right, he will walk right etc.

class Player(pygame.sprite.Sprite):
def __init__(self): #constructor
    pygame.sprite.Sprite.__init__(self) #constructor for the sprite
    self.playerPicture = pygame.image.load('JumpLeft.png')
    self.runRight = pygame.image.load('RunRight2.png')
    self.runLeft = pygame.image.load('RunLeft2.png')
    self.jump = pygame.image.load('Jump.png')
    self.playerPicture = self.playerPicture.convert_alpha()
    self.rect = self.playerPicture.get_rect()

    self.standingStill = pygame.image.load('JumpLeft.png')
    self.playerx = windowWidth / 2
    self.playery = windowHeight - 200
    self.direction = None
    self.onGround = False
    self.isJumping = False;
    self.gravity = 1.2
    self.velocity = 0

    self.rect.center = (self.playerx, self.playery)

Current attempts:
So far i've tried

if direction == 'UP':
   player.playery -= 2

which the character pretty much just continuously moves up until the user releases the space button


texts: Efficient way to draw multiple separated quads

texts:
Let's assume I want to draw several separated (possibly textured) quads in Direct3D 9, each consisting of two triangles:

How should I draw these for maximum performance, i.e. which of the following ways is better in terms of speed?

Describe each quad by 4 vertices, use D3DPT_TRIANGLESTRIP and call IDirect3DDevice9::DrawPrimitive for each individual quad, since they are not connected.
Describe each quad by 6 vertices, use D3DPT_TRIANGLELIST and call IDirect3DDevice9::DrawPrimitive just once.

The first method uses less memory, while the second one requires only one draw call.

However, the second way seems to be feasible only if all the quads have the same texture, since otherwise a switch would be required.


texts:
Can i fusion multiple .tga or .jpeg into only one, and texturise my model with it ?

Here is an example to explain my self better :  I have Mr Bowser as 3d model and i want to integrate it in a game. The thing is that all the textures, from the color of his mouth to the cones on his shell are held by different tga files. For the mouth i have mouth.tga as texture, for the cones on the shell i have cone.tga and so on... . But what i want to achieve is to have cone.tga mouth.tga and so on, in the same and only file. Like all the textures to make Mr angry Bowser a colorfull character concentrated in one and only file.
Can i achieve that, is there a way to do it ?

Any help will be much appreciated.
Thank you.


texts: I believe there's a D3DX function that can load a DDS file with mipmaps but D3DX is deprecated. Any function/library that can load it and that's not deprecated? I need it for DirectX if it makes any difference.


texts:
I get an error while trying to build a game for webgl. I have created a new 3d project with only a cube in it and have not created any scripts. When I try to build and run the webgl option, these are the errors I get.

    Failed running "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"G:\webgl\Assets\..\Temp\emcc_arguments.resp"

stdout:
stderr:INFO:root:Checking JS engine ['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096'] failed. Check your config file. Details: [Error 5] Access is deniedCRITICAL:root:The JavaScript shell (['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096']) does not seem to work, check the paths in the config file
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

UnityEditor.BuildPlayerWindow+BuildMethodException: 3 errors
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002bb] in <480b5a3bd3214ce5831f6dd8c68fdc55>:0
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <480b5a3bd3214ce5831f6dd8c68fdc55>:0
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

This is what the editor log shows:

C:\Program Files\Unity\Hub\Editor\2019.3.13f1\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe exited after 228169 ms.
Filename: "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe"
Arguments: -E "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"G:\webgl\Assets\..\Temp\emcc_arguments.resp"
index: -1
Failed running "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Hub/Editor/2019.3.13f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"G:\webgl\Assets\..\Temp\emcc_arguments.resp"

stdout:
stderr:INFO:root:Checking JS engine ['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096'] failed. Check your config file. Details: [Error 5] Access is deniedCRITICAL:root:The JavaScript shell (['G:\\nodejs\\node_modules\\npm\\bin', '--stack_size=8192', '--max-old-space-size=4096']) does not seem to work, check the paths in the config file

I'm not sure how to resolve this....Can someone please help...


texts: Using InputListener touchDown - Unable to jump while pressing direction button

texts:
Using InputListener attached to images for touchscreen control I initially had the problem of the player being able to continuously jump and fix themselves to the top of the screen by simply holding the jump button.

This was resolved by adding a gdx.input.justTouched() check before calling the jump() method. However, this annoyingly then introduced a new issue of not being able to jump whilst holding a direction button. The direction button first has to be released before the jump will function.

if (player.presentState != Player.State.DEAD && player.presentState != Player.State.WIN) {
            if (controller.isRightPressed() && player.body.getLinearVelocity().x <= 1.75)
                player.body.applyLinearImpulse(new Vector2(0.1f, 0), player.body.getWorldCenter(), true);
            if (controller.isLeftPressed() && player.body.getLinearVelocity().x >= -1.75)
                player.body.applyLinearImpulse(new Vector2(-0.1f, 0), player.body.getWorldCenter(), true);
            if (controller.isUpPressed() && controller.isJumpPressed() && player.presentState != Player.State.FALLING)
                if (Gdx.input.justTouched()){
                    player.superJump();
                }
            if (controller.isDownPressed()){
                player.dive();
            }
            if (controller.isJumpPressed() && player.presentState != Player.State.JUMPING){
                if (Gdx.input.justTouched()) {
                    player.jump();
                }

The jump() method operates under two different state conditions.

If the player is state.ground or state.running, a positive y-impulse is applied.

If the player is state.falling a slight positive y-impulse is applied with linearDampening allowing the player to control the descent as to float/glide down.

This all works perfectly via my keyboard input implementation but not in my touchscreen one.

How to resolve this?


texts: Creating an unbiased deterministic collision resolution order

texts:
I'm working on a game with a replay system, so I need the game logic to be deterministic. A part of this is collision detection and I'm having a bit of a conceptual problem here. (I'm programming in Python but I think my question is more general than that.)

I need collisions to be solved in a deterministic unbiased order. For example, it would be unfair if collisions would always be solved first for the red team, because e.g. they would always collide with (and thus pick up) ammo first. I can't imagine I'm the first person experiencing this problem.

The way the engine works is somewhat as follows:

Until no objects colliding:

Find overlapping objects and separate them
Add the object pair to a "collided" set (so no duplicates).

Finally:

Sort the "collided" set based on some property.
Iterate through "collided" set and tell each object pair that they collided with the other object.

Is there a way to sort the set for this final iteration while keeping it fair?

Things that won't work:

Memory location (python's default for sorting objects) because this is nondeterministic.
Internal object ID's, because these ID's are always lower for the "red team", as they are added first.
X/Y coordinates, don't give a complete sorting order, because objects can have identical positions, additionally, this is biased because the "red team" spawns at X=0.


texts: Is moving entities between sectors of a grid spatial partitioning inefficient?

texts:
I'm using a grid system for spacial partitioning. If I have moving entities, will I have to reassign every entity to its correct section every frame?

Surely this is inefficient. Have I got the wrong idea?


texts: I keep coming across an error "Cannot read property 'innerHTML' of undefined"

texts:
I'm new to game designing and have to create a game for my project but I keep coming across an error to do with:

index.html:93 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
at drawMissiles (index.html:93)
at gameLoop (index.html:140)

Any idea how to fix this problem?
    drawMissiles()
}

function drawMissiles() {
  document.getElementsByTagName('missile')[0].innerHTML   <--- (index.html:93)
    for(var i = 0 ; i < missiles.length ; i++ ) {
        document.getElementById('missile').innerHTML +=
             `

`;


texts: Best next step for game AI implementation

texts:
I have recently finished a small framework that employs agents governed by a small hierarchical finite state machine, however I have quickly discovered the drawbacks of this approach. Namely the fact that increasing numbers of behaviours call for an exponentially complicated rule-base to govern the switches.

It occurs to me that there is probably a much better way of coding AI, where they have overall goals and can assess new information with regards to this.

I did some research but was a little overwhelmed by the amount of methodologies, and for that matter the lack of information about which techniques are more commonly used and which are best for certain situations.

what would be a good next implementation/methodology for a 3rd / 1st person shooter? such as a neural network or GOAP.


texts: Strategies to make it difficult to cheat + easier to identify cheaters in Javascript/HTML5 game

texts:
I intend to have a Javascript/HTML5 game with a global leaderboard. I have devised a very simple system for submitting highscores as follow:

  When the game finishes, the game client makes a POST request to server hosting the leaderboard that contains the name of the player and their score. Then, the server inserts the submission into its database.

However, this system can easily be cheated by an individual with an html form submitting POST requests with whatever score they want to my server.

I already know that a foolproof anti-cheat system is impossible because of how easy it is to modify Javascript and HTML on the client. I also know that I should never trust the client. However, implementing everything on the server side will be impractical for me since my server will not have the resources necessary to perform all the calculations for all the players.

So instead, I simply wish to make it as hard as possible for the average individual to cheat (and recognizing that it will always be possible to cheat), while making it as easy as possible for me to identify when a score that was submitted might possibly be fake.

What are strategies I can use to accomplish such? Please include examples whenever possible. For example, I have heard someone suggest using "pre-shared keys". However, I am not a cryptography expert and I have no idea how to go about implementing that.


texts: how disable texture after drawing an object?

texts:
i try to make a textured object then draw other without (only colored).

i had tried to play with glEnable/Disable(GL10.GL_TEXTURE_2D) ,         gl.glEnable/DisableClientState(GL10.GL_COLOR_ARRAY/GL10.GL_TEXTURE_COORD_ARRAY);

But i never get the result i expect.

(first colored + textured then others textured and colored too)
(first colored and not textured then other colored and not textured)

i don't know if this is because i don't disable some things at the good place or if i missing something.


texts: Anybody know how I can write a game for the dualshock 3 or other gampad in python?

texts:
I am a new developer and want to write a game that uses a gamepad like the dualshock 3 I want to write it in python although am willing to learn a little C/C++

I need to identify the buttons and rotaters and send feedback like haptics not to mention the motion control


texts: How can I stop the endless output in Unity console?

texts:
I want to print the sum of two numbers, but only when I press the enter key. Pressing any other key should give me the message "Invalid Key".
Now the output I am getting is an endless loop of "Invalid key", until I press another button.

How do I only produce the output when I press a key?

using UnityEngine;
using System.Collections;

public class LearningScript : MonoBehaviour {

    public int number1 = 5;
    public int number2 = 10;
    public bool condition;
    public int answers;

    void Update()
    {
        if (Input.GetKey (KeyCode.Return))
            condition = true;
        else
            condition = false;

        if (condition)
            Debug.Log (answers);
        else
            Debug.Log ("INVALID KEY");
    }

    void Start()
    {
        answers = addTwonumbers (number1, number2);
    }

    int addTwonumbers(int num1,int num2)
    {
        int result = num1 + num2;
        return result;
    }
}


texts:
I have this code:

char shaderName[128] = "";//the name of the file
char text[1024 * 16] = "";//the content of the file
std::ofstream myfile;//the file
myfile.open(shaderName + ".shader");//i want to concatenate the file name with the .shader extension
myfile << text;//put the content of the text array in the file
myfile.close();//close the file

This gives me an error. It tells me i can't convert a char array to a string or const char*. I want to be able to concatenate the nameof the file with the .shader extension. I also tried to cast shaderName to an (std::string) or a const char*

EDIT:

ImGui::Begin("Shader Writer");

char text[1024 * 16] = {""};

char shaderName[128] = {""};

ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetWindowHeight()), ImGuiInputTextFlags_AllowTabInput | (false ? ImGuiInputTextFlags_ReadOnly : 0));

    ImGui::Text("Shader Name: ");
    ImGui::InputText("", shaderName, IM_ARRAYSIZE(shaderName));

    ImGui::SameLine(0.0f, 2.0f);

    if(ImGui::Button("Create", ImVec2(50, 20)))
    {
        char shaderName[128] = "";

        std::ofstream myfile;

        std::string name(shaderName);
        std::string FileName = name + ".shader";

        myfile.open(FileName.c_str());
        myfile << text;
        myfile.close();
    }

    ImGui::End();

The InputTextMultiline() function let's you modify,write,read a text. The "text" in this case is a char array(this function outputs a char array).
Then we have another InputTextMultiline() function which also returns a char array. In order to use this data returned by these functions, i need to convert them to strings(or maybe to const char*,even tho i think std::strings is better).

Here is a rapresentation of what these functions do:


texts: Recording and playing back sounds with LibGDX

texts: How do I record a sound to PCM format and replay it from there?


texts: Unity error: type "x" exist in both 'A' and 'B'

texts:
I just opened a project made in unity version 2018.1.1f into Unity version 2020.1.1f
I know opening the older projects is not supported by Unity but it opened fine.
The only problem is that it is giving an error which looks like this-
What I tried:

checking the script onetizationPlatform.cs to ensure nothing is wrong in it
checked that there's no two files with same name unitylifecyclemanager
doing point 2 with unityengine.advertisement.editor
deleting unityengine.advertisement.editor which caused another error so I had to restore it back


texts: Why does my goblin only choose a walk direction once?

texts:
I'm working on a simpe 2d canvas game that has a small goblin sprite who I want to get pathing around the screen.

What I originally tried was a random roll that would choose a direction, the goblin would walk that direction. It didnt work effectively, he sort of wobbled in one spot.

Here's my current apporach but he only runs in a rundom direction and doesnt change. What am I doing wrong?

Here's all the relevant code to the goblin object and movement.

    var goblin = {
            speed: 100,
            pos: [0, 0],
            dir: 1,
            changeDir: true,
            stepCount: 0,
            stepTotal: 0,
            sprite: new Sprite(
                                goblinImage,
                                [0,0],
                                [30,45],
                                6,
                                [0,1,2,3,2,1],
                                true)
    };

    function getNewDir(){
            goblin.dir = Math.floor(Math.random()*4)+1;
    };

    function checkGoblinMovement(){
        if(goblin.changeDir){
            goblin.changeDir = false;
            goblin.stepCount = 0;
            goblin.stepTotal = Math.floor(Math.random*650)+1;
            getNewDir();
        }
        else
         {
           if(goblin.stepCount === goblin.stepTotal){
                 goblin.changeDir = true;
         }
       }
    };

    function update(delta){

        healthCheck();

        if(isGameOver){
            gameOver();
        }
        if(!isGameOver){
        updateCharLevel();
        keyboardInput(delta);

        moveGoblin(delta);
        checkGoblinMovement();

        goblin.sprite.update(delta);

        //update sprites
        if(mainChar.kills!=0 && bloodReady){
            for(var i=0; i<bloodArray.length; i++){
                    bloodArray[i].sprite.update(delta);
         }
        }

        //collision detection
        if(collision(mainChar, goblin))
            {
               combatOutcome(combatEvent());
               combatCleanup();
            }
            }
        };

    function main(){
        var now = Date.now();
        var delta = (now - then)/1000;
        if(!isGameOver){
        update(delta);
        }
        draw();
        then = now;
    };

function moveGoblin(delta){

    goblin.stepCount++;

    if(goblin.dir === 1){
      goblin.pos[1]  -= goblin.speed * delta* 2;
        if(goblin.pos[1] <= 85){
            goblin.pos[1] = 86;
          }
    }

    if(goblin.dir === 2){
        goblin.pos[1]  += goblin.speed * delta;
        if(goblin.pos[1] > 530){
            goblin.pos[1] = 531;
          }
    }

    if(goblin.dir === 3){
      goblin.pos[0]  -= goblin.speed * delta;
        if(goblin.pos[0] < 0){
            goblin.pos[0] = 1;
          }
    }

    if(goblin.dir === 4){
      goblin.pos[0]  += goblin.speed * delta* 2;
        if(goblin.pos[0] > 570){
            goblin.pos[0] = 571;
          }
    }

};


texts:
I am trying to re-create this:

So what I did is, made an half-circle image, filled with red, and set a TextureRegion, and used setRegionHeight for given percentage:

public void setDamage(int d) {
    int height = damage.getTexture().getHeight();

    double val = (double) d / 100;
    damage.setRegionHeight((int) Math.round(val * height));
}

I did the same for the water one

And called after creating:

water.flip(false, true);
bilge.flip(false, true);
setDamage(70);
setWater(30);

I had to flip it aswell y-wise.

And it looks like this:

Doesn't look right, because it fills in a straight line, like I guess it would.

What methods can I use to create that filling look? I know I can use ShapeRenderer but I am not sure how, maybe use the circle equation and use half circle and fill lines at each degree based on the percentage set on damage? I would be happy to get some ideas


texts: small independent game development on a virtual machine

texts:
I've been learning about OpenGL and SFML  with c++ now for about 6-8 months, and would like to work on a small little personal game to put some of my skills to the test.

Now I want to kill two birds with one stone, and also increase my knowledge of Ubuntu and linux development in general by developing this project in Ubuntu. Currently my main computer runs Windows 7 while I have an older computer than runs Fedora 18, so I set up an ubuntu 12.04 LTS virtual machine on my main computer. The problem is, what effects does this have graphics wise? I know windows virtual machines running games can often have some graphical and input bugs, should I not use a virtual machine? Or this fine and I'm simply over thinking the subject? Thanks!

Note**

I am using VM VirtualBox on my windows 7 desktop.


texts: uNet - Client cant see server spawned objects

texts:
I'm facing a problem where when I connect with the host, all the towers spawn. After I connect with a client only to find out there are no towers visible and I can walk through them when looking at the host screen.

My tower spawn script ( GameManager.cs ) :

public int numberOfDestroyedTopTowers = 0;
public int numberOfDestroyedMidTowers = 0;
public int numberOfDestroyedBotTowers = 0;

public GameObject[] topTowerSpawns;
public GameObject[] midTowerSpawns;
public GameObject[] botTowerSpawns;

public GameObject towerPrefab;

void Start() {
    CmdSpawnTowers();
}

[Command]
void CmdSpawnTowers() {

    for (int i = 0; i < midTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = midTowerSpawns[i].transform.position;
        currTower.name = "Tower [MID] " + i;
        NetworkServer.Spawn(currTower);
    }

    for (int i = 0; i < topTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = topTowerSpawns[i].transform.position;
        currTower.name = "Tower [TOP] " + i;
        NetworkServer.Spawn(currTower);
    }

    for (int i = 0; i < botTowerSpawns.Length; i++) {
        GameObject currTower = (GameObject)Instantiate(towerPrefab);
        currTower.transform.position = botTowerSpawns[i].transform.position;
        currTower.name = "Tower [BOT] " + i;
        NetworkServer.Spawn(currTower);
    }

}

The script is derived from NetworkBehaviour and it does have a Network Identity on it (Server Only checked). Also on my towerPrefab I also have a network identity with server only checked.
I have added my tower prefab under the network manager "Registered Spawnable Prefabs".


texts: I've made a character design and added Rigidbody 2D and Box Collider 2D to it but when I put it on top of the ground which is in tiles in a tilemap it floats on top i.e. the tilemap consists of a hill going up then down but when I put it on the ground it goes up again in a position level to the peak of the hill   and even on top of hill it floats a little above the grid line


texts:
My UI :

An UI from YouTube video :

Look my camera's size is 10 and his camera's size is only 5. But, my camera's width is larger than height. If you look at scale (x,y,z)=(1,1,1). I tried to change them. But, nothing changes.I tried to change ViewPort Rect then, I am able to change the size of Main Camera. But, look at following image. His ViewPort Rect is 1 by 1 mine also. But, we have differences of width and height.
How to fix it?


texts: Box2D platformer movement. Are joints a good idea?

texts: So i smashed my brains trying to make my character move. As i wanted later in the game to add explosions and bullets it wasn't a good idea to mess with the velocity and the forces/impulses didn't work as i expected so something stuck in my mind: Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation? I will attach this to my main body with a revolute joint but i don't really know how to make the main body and wheel body to don't collide one with each other since funny things can happen. What is your oppinion?


texts:
Can anyone recommend a tile map generator (written in Java is a plus), where one can control some land types? For example: islands, large continents, singe large continent, archipelago, etc.

I've been reading through many posts on the subject, it almost seems like many are just rolling their own. Before creating my own, I'm wondering if there's already an open source implementation that I might not be finding.

If not, it seems like using Perlin Noise is a popular choice.

Some articles I've been reading:

http://simblob.blogspot.com/2010/01/simple-map-generation.html

Generate islands/continents with simplex noise

https://sites.google.com/site/minecraftlandgenerator/


texts: How Frustum Culling and Sky Box Working Together ? The skybox appears where it should not appear

texts:
When i did frustum culling, far parts of land not rendering. It is good like i want. But after I see sky box instead of these parts. My question is, is this normal ? Or what i need to see or what i need to do ? Because it doesn't look nice in the game.

I will show my problem to you with pictures. Over "Blender" program.

I ADDED NEW PICTURE:


texts: How can I use more than one mouse connected to the same computer as different input devices in Unity?  I want to read the input axis of each mouse individually for local multiplayer games.


texts:
I want to implement something like this to create a heightmap: 'Place a group of coordinates evenly across a map, and give them height values within a certain range. Repeatedly create coordinates between all of those coordinates, setting their height by deriving a value that was a mean value of all the surrounding coordinates.'

However, I'm not sure how I would go about it - I'm not sure how I could code the part where I place the coordinates in between the existing coordinates. Can anyone give any help/advice?


texts: How to rotate one object around another moving object in 3-d?

texts:
i was wondering if anyone could give me some advice on how to rotate one object around another moving object. After a bit of googling i found some code on another website that worked perfectly but it would only work on staitionary objects. The code that i used:

Vector3 temp = objectPosition - objectToRotateAboutPosition;
temp = Vector3.Transform(temp, Matrix.CreateRotationX(angle));
objectPosition = objectToRotateAboutPosition + temp;

It works perfectly on the staitionary object but on a moving object it seems to object that is orbiting the main object seems to distance itself a great distance before it returns to the original position. I was wondering if anyone knew a way that i could tweak this code blocka and make it work, or maybe a different way to rotate one object around a moving object.


texts: Which camera angle is used for these sprites?

texts:
I am trying to replicate these sprites:

But I am not managing to make sense of how it is done. The character is facing forward ( <--- ), but you can see the front of its body instead of just the side. Why? Is the camera positioned diagonally? Or is the body bent, as in a fighter stance?

Or a combination of both?

Which exactly is the positioning/perspective/view I should use to replicate it correctly?


texts:
I'm a beginner using OpenGL v3.3 on C# with SharpGL. I have a simple scene with a Skybox and some OBJ Models. Both the skybox and models have multiple textures. Currently what I do is that I load all the textures used in the scene into different texture units at once program launch and then while rendering each element in the scene I just change a uniform variable to reflect the correct texture unit and render the vertices. Doing this could get me into trouble if there are more textures in my scene than texture units on the GPU, so I'm not sure if this is the right approach.

I would like to know what the standard practice for such a scenario. Do you just (re)load the texture for each element into say fixed texture unit 0 on every draw call or what?


texts: Data Structures for Logic Games / Deduction Rules / Sufficient Set of Clues?

texts:
I've been cogitating about developing a logic game similar to Einstein's Puzzle , which would have different sets of clues for every new game replay.

What data structures would you use to handle the different entities (pets, colors of houses, nationalities, etc.), deduction rules, etc. to guarantee that the clues you provide  point to a unique solution?

I'm having a hard time thinking about how to get the deduction rules to play along with the possible clues; any insight would be appreciated.


texts:
I have a list of lazers(bullets) that i would like to delete specific instances from.  How would I go about doing that with the code I have now?
I first tried to pass in the player to a lazer instance and if that lazers out of bounds delete by indexing the lazer table with its id and setting that to nil.  But then the lazers stopped working with that logic.  Setting lazer to nil inside its own update function doesnt work either.(self = nil)
Lazer = Class("Lazer")
Lazer.isLazer = true
Lazer.count = 0
function Lazer:init(x,y,speed,rax,ray)
    self.position = Vector2(x,y)
    self.speed = speed
    self.velocity = Vector2(rax,ray):unit()
    self.id = Lazer.count
    Lazer.count = Lazer.count + 1
end
function Lazer:update(dt)
    self.position = self.position + self.velocity * self.speed * dt
    if not isPointWithinRect(self.position.x,self.position.y,0,0,windowWidth,windowHeight) then
       --what do i do here?
    end
end
function Lazer:draw()
    love.graphics.setColor(255,255,0)
    love.graphics.circle("line",self.position.x,self.position.y,5,5)
end

Player = Class("Player")
Player.isPlayer = true
function Player:init(joystick,x,y,speed)
    self.joystick = joystick
    self.position = Vector2(x,y)
    self.velocity = Vector2(0,0)
    self.speed = speed
    self.acceleration = acceleration
    self.terminal_velocity = terminal_velocity
    self.lazzer_speed = speed + 25
    self.lazers = {}
    self.timer = 0
end
function Player:update(dt)
    self.timer = self.timer + dt
    local lax,lay = self.joystick:getAxes()
    self.velocity.x = lax
    self.velocity.y = lay
    if math.abs(lax) > .1 or math.abs(lay) > .1 then
        self.velocity = self.velocity:unit()
    end
    self.position = self.position + self.velocity * self.speed * dt
    self.position.x = clamp(self.position.x,0 + 20,windowWidth - 20)
    self.position.y = clamp(self.position.y,0 + 20,windowHeight - 20)
    local _,_,rax,ray = self.joystick:getAxes()
    if (math.abs(rax) > .1 or math.abs(ray) > .1) and self.timer > .1 then
        table.insert(self.lazers,Lazer(self.position.x,self.position.y,self.speed + 250,rax,ray))
        self.timer = 0
    end
    for _,v in pairs(self.lazers) do
        v:update(dt)
    end
end
function Player:draw()
    love.graphics.setColor(255,255,255,255)
    love.graphics.circle("line",self.position.x,self.position.y,15,30)
    for _,v in pairs(self.lazers) do
        v:draw()
    end
end
```


texts:
In my research for a stuttering problem in my game engine, I think, I have found the problem, but don't have any idea why this is happening, that's why I ask you if you have an idea !

The situation :
DirectX10 under win7 simple engine. If running fullscreen (and only in fullscreen), with Vsync On and the rendering loop going much more faster than the vsync ==> Stutter (Frame dropped by the driver).

My base solution at this moment : Make the call to device.present() not faster than the Vsync !

My questions :
- What is happening here ? It seems that the called to .present() "is caching" frames, and if the cache is full, it can go to throw away a frame ==> It makes the stutter !
- Why is it not happening in windowed mode under the exact same situation (back buffer resolution, scene, ...) ???

Edit :
Here is a Pix debugging screen (big picture), showing the stuttering :
http://www.s33m3.be/PIX/PIX3.png
You can see that frame 912, that did exactly the same amount of work as other frames, wasn't processed by the GPU. (No GPU start/Duration). And after debugging, it just that for this frame the call to .Present() was really low (more then 10 times faster than the average .Present() of the other frames !

So how can I disable in DirectX10  this "feature" to throw aways frames ? I would prefer the Present method to hold instead of dropping a frame !


texts: Transfer mouse movements to a GameObject in 3D according to camera position and rotation

texts:
I'd like the game object to follow the mouse but I have trouble doing this when the object is in 3D and the camera has been rotated.

The only thing that seems to be true (and still it works only when camera isn't rotated) is :

The visible X for the camera is equal to 2 * Mathf.Abs(object.position.z - camera.position.z)
The visible Y for the camera is equal to VisibleX * (camera.pixelHeight / (float)camera.pixelWidth) (casting to float to avoid int divided by int returning an int)


texts: Box2D - Do these simple objects need to be in the simulation?

texts:
I would like to get input from the community regarding how best to represent simple objects in a Box2D based simulation.

Some background:
Without going into too much detail, think of a top down game with a character and some 'food'. You can picture PacMan™ even. Suppose I will simulate the character and the walls to be Box2D so the guy cannot leave the maze and I get collision feed back etc.

My question:
Should the 'food' be part of the Box2D simulation?

My thoughts:

The food doesn't need to be in the simulation because..
It doesn't move.
As soon as the character collides with the food it is removed from the game.
It should not apply any force to the guy, or anything, ever.
Nor should anything ever need to apply force to it.
It's extra computation that isn't necessary.

The food could be in the simulation because..
I am already using Box2D.
Box2D can handle the collision events for me.
Again, Box2D can handle the collision events for me; I don't really want to check for collisions myself.
Box2D should let the food 'sleep' so it won't be much extra computation, correct?

What do you guys think? Do the benefits outweigh the costs here? Are there other pros/cons I'm missing?

I look forward to getting feedback.


texts:
How do we solve big video memory requirements in a 2D game?

We are developing a 2D game (Factorio) in allegro C/C++, and we are facing a problem with increasing video memory requirements as the game content increases.

We currently gather all the info about images that are going to be used first, crop all of these images as much as possible and organize them into big atlases as tightly as possible. These atlases are stored in video memory, the size of which depends on the system limitations; currently it is usually 2 images of up to 8192x8192, so they require 256Mb to 512Mb video memory.

This system works pretty good for us, as with some custom optimisations and splitting the render and update thread we are able to draw tens of thousands of images on the screen in 60 fps; we have many objects on the screen, and allowing a big zoom-out is a critical requirement. As we would like to add more, there is going to be some trouble with the video memory requirements, so this system can't possibly hold.

One of the things we wanted to try is to have one atlas with the most common images, and the second as a cache. The images would be moved there from the memory bitmap, on demand. There are two problems with this approach:

The drawing from memory bitmap to video bitmap is painfully slow, in allegro.
It is not possible to work with video bitmap in other than the main thread, in allegro, so it is practically unusable.

Here are some additional requirements we have:

The game must be determistic, so the performance issues/loading times can never alter the game state.
The game is real time, and soon to be multiplayer, as well. We need to avoid even the smallest stutter at all costs.
Most of the game is one continuous open world.

The test consisted of drawing 10 000 sprites in a batch for sizes from 1x1 to 300x300, several times for every configuration. I did the tests on the Nvidia Geforce GTX 760.

Video bitmap to video bitmap drawing took 0.1us per sprite, when the source bitmap wasn't changing between individual bitmaps (the atlas variant); the size didn't matter
Video bitmap to video bitmap drawing, while the source bitmap was switched between drawings (non atlas variant), took 0.56us per sprite; the size didn't matter, either.
Memory bitmap to video bitmap drawing was really suspicious. Sizes from 1x1 to 200x200 took 0.3us per bitmap, so not so horribly slow. For larger sizes, the time started to raise very dramatically, at 9us for 201x201 to 3116us for 291x291.

Using atlas increases the performance by a factor greater than 5.
If I had 10ms for the rendering, with an atlas I'm limited to 100 000 sprites per frame, and without it, a limit of 20 000 sprites. This would be problematic.

I was also trying to find a way to test the bitmap compression and 1bpp bitmap format for shadows, but I was unable to find a way to do this in allegro.


texts: Rotate a 2D object slowly to the touch position in Unity

texts:
I am creating a circular Joystick like setup in Unity. Played a lot with it in different ways but I don't get the desired results.

void Update()
     {
         //movement = Input.GetAxisRaw("Horizontal");
         if (Input.touchCount > 0)
         {
             touch = Input.GetTouch(0);
             if (touch.phase == TouchPhase.Began)
             {
                 firstTouchY = touch.position.y;
             }

             if (touch.phase == TouchPhase.Moved)
             {
                 if (touch.deltaPosition.y < 0)
                 {
                     movement = -1;
                 }
                 else if (touch.deltaPosition.y > 0)
                 {
                     movement = 1;
                 }
                 rotatePlayer();
             }
         }
     }

     private void rotatePlayer()
     {
         transform.RotateAround(Vector3.zero, Vector3.forward, movement * Time.fixedDeltaTime * moveSpeed);
     }

This is what I want.


texts: How to process events as well as do OpenGL rendering using multithreading?

texts:
I am working on a very complicated graphics rendering, using OpenGL, and it is very time consuming, in the sense that it creates a delay in the event handling, of my application to an extend that, the OS will think my application is freezing !
Therefore, I was thinking of running two threads, one for the OpenGL rendering and the other for event handling. But, I dont think this is possible for my current framework that I'm using!
Basically, I'm using SDL 2.0 to set up an OpenGL context, and then using vertex and fragment shaders to do the rendering.
Code:
// Initialize OpenGL context
// Set up VAO, VBO, compile vertex/frag. shaders, link, use program  etc.
//
bool run = true;
SDL_Event e;
while(run)
{
       glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
       render(); // Complicated rendering :(
       SDL_GL_SwapWindow(window);
       while(SDL_PollEvent(&e))
       {
             switch(e.type){
                   case SDL_QUIT:
                        run = false;
                        break;
             }
       }
}

As you might realize if render is slow,  then event handling will lag. This might crash my application !
The SDL library wants everything in the same thread I guess. If I move the event handling part to another thread, then OpenGL won't render anything! Similarly, if I move the OpenGL based render function to another thread, still it won't render anything!!! In fact event handling is a must for SDL in particular and to the OS  in general.
What is the practical remedy to this issue?


texts: How can I get started programming OpenGL on Mac OS X?

texts:
I'm trying to start OpenGL programming on a Mac, which brings me into unknown territory on a lot of things.

During the day, I'm a Web Developer, working in C# and before that in PHP and Delphi, all on Windows.

During the night, I try to pick up Mac/OpenGL skills, but everything is so different. I've been trying to look for some books, but the OpenGL books are usually for iOS (tons of them out there) and the Mac Books usually cover "normal" application Development.

I want to start simple with Pong, Tetris and Wolfenstein.

I see that there are a bunch of different OpenGL Versions out there. I know about OpenGL ES 1&2, but I don't know about the "big" OpenGL Versions - which ones are commonly supported on 10.6 and 10.7 on current (2010/2011) Macs? Are there any up to date (XCode 4) books or tutorials?

I don't want to use a premade Engine like Unity yet - again, I know next to nothing about any Mac development.


texts:
I'm making a Minecraft like game and I would like to apply some optimizations. Firstly I didn't and I rendered the world using a vbo in which I stored a cube model and I drow all blocks of the worlds and off course it caused lag if there were too many blocks.
Then I decided to draw the world face-by-face and check if a face is hidden from another one.

This concept is simple if I have the world made only by cubes of the same size, like this:

Blue and black block are two blocks of the same size and the red face is the face to ignore since is hidden (overlapped) by another opaque face.

As I said if I want to make blocks of different sizes (scale)/position/rotation but by always drawing them from faces, the matter is different since I can't know if a face is completely visible or not. Here's an image of a normal block with a "custom" block on it:

Blue block is the custom block, the black a "normal" block and the red is the face overlapped by the biggest one (then it should be ignored during rendering).

Here the rotation is null but if there's no way to check rotated faces I can simply ignore it and draws all rotated blocks by default (I don't rotate all the world lol)... that's not what I'd like to do but if there's no way or the way is too difficult...

Anyway, finally, how can I check (using GL functions or doing it in my code) if a face is hidden and to ignore it on rendering?

I forgot to say that another optimization I did is if a block is hidden (has a block relative to each face) by other blocks I don't draw it.


texts:
I am using the following code, my intention is whenever the 2 objects meet the animator boolean changes and when leave change back to its original setting. But it doesnt seem to work.

  public GameObject ThePlayer;
public float TargetDistance;
public float EnemyHealth;
public float AllowedRange = 10;
public GameObject TheEnemy;
public float EnemySpeed;
public Animator animator;
public int AttackTrigger;
public RaycastHit Shot;
public static bool hasAttacked = false;
private bool gapTest = true;

void Start()
{

    animator = GetComponent<Animator>();
    hasAttacked = false;
}

void OnCollisionEnter(Collision col)
{

    if (col.gameObject.name == "FPSController")
    {
        Debug.Log("hit");
        animator.SetBool("Moving", false);
        animator.SetBool("Attack1Trigger", true);
        hasAttacked = true;
    }

}

void OnTriggerExit(Collider col)
{
    if (col.gameObject.name == "FPSController")
    {
        Debug.Log("left");
        animator.SetBool("Moving", true);
        animator.SetBool("Attack1Trigger", false);
        hasAttacked = true;
    }
}

Any tips on why this does not work?

This is hitting the debug.log in the console, but it is not hitting the animator changes or the boolean change


texts: Why does my mesh disappear from certain angles?

texts:
I'm trying to construct a hexagonal prism from vertices for my turn-based strategy game. This is my first time working with meshes and I have been following this tutorial.

The problem I am having is that the sides of my shape disappear at certain angles (in this example, I only rendered the top, bottom, east, and west sides).

I have tried removing the main camera and lighting from the scene. I have tried using RecalculateBounds() but that had no effect and besides, Unity's documentation says it's not needed when assigning triangles.

The whole thing gets rendered if I position the camera perfectly, so I don't imagine I'm calculating vertices incorrectly or anything like that. Is there something I should know about Unity meshes that would cause this to happen?


texts:
I'm currently working on an idea for a Unity game app with a canvas mechanic. I understand I may have to use particles for the brush/paint f/x however I can not think of a way to add collision detection let alone the paint itself...onto a canvas...
Any suggestions are much appreciated!


texts: Why do physics engine use impulses to solve collisions?

texts:
Usually, in most physics engines that are out there, the way that collisions are solved is by applying some impulse to both colliding bodies.

While I understand that impulses are just force that is already integrated into time, and will result into velocity added at the end of the frame, why not simply project both bodies out of collision and removing their velocity component that is going towards the collision?

I'm not really sure, but it really looks like classic platformers only stopped the character instead of adding impulse to it. Is this right?

And if yes, why the added complexity of using impulses in modern engines?


texts: Why can't a blendShader sample anything but the current coordinate of the background image?

texts:
In Flash, you can set a DisplayObject's blendShader property to a pixel shader (flash.shaders.Shader class).

The mechanism is nice, because Flash automatically provides your Shader with two input images, including the background surface and the foreground display object's bitmap.

The problem is that at runtime, the shader doesn't allow you to sample the background anywhere but under the current output coordinate.  If you try to sample other coordinates, it just returns the color of the current coordinate instead, ignoring the coordinates you specified.  This seems to occur only at runtime, because it works properly in the Pixel Bender toolkit.

This limitation makes it impossible to simulate, for example, the Aero Glass effect in Windows Vista/7, because you cannot sample the background properly for blurring.

I must mention that it is possible to create the effect in Flash through manual composition techniques, but it's hard to determine when it actually needs updated, because Flash does not provide information about when a particular area of the screen or a particular display object needs re-rendered.  For example, you may have a fixed glass surface with objects moving underneath it that don't dispatch events when they move.  The only alternative is to re-render the glass bar every frame, which is inefficient, which is why I am trying to do it through a blendShader so Flash determines when it needs rendered automatically.

Is there a technical reason for this limitation, or is it an oversight of some sort?  Does anyone know of a workaround, or a way I could provide my manual composition implementation with information about when it needs re-rendered?

The limitation is mentioned with no explanation in the last note in this page: http://help.adobe.com/en_US/as3/dev/WSB19E965E-CCD2-4174-8077-8E5D0141A4A8.html  It says:

  "Note: When a Pixel Bender shader program is run as a blend in Flash
  Player or AIR, the sampling and outCoord() functions behave
  differently than in other contexts.In a blend, a sampling function
  will always return the current pixel being evaluated by the shader.
  You cannot, for example, use add an offset to outCoord() in order to
  sample a neighboring pixel. Likewise, if you use the outCoord()
  function outside a sampling function, its coordinates always evaluate
  to 0. You cannot, for example, use the position of a pixel to
  influence how the blended images are combined."


texts: What would be theoretical the perfect texture size?

texts:
I am more a newbie considering game development but I am dealing very often with optimization of games for work and because I am interested in it.

So as far as I know higher texture size need less draw calls if you make serveral objects share the same texture but it takes up more VRAM.
Also you have to consider how acuit you want to have your textures.

But the more I thought about the topic I thought there would be a theoretical perfect texture size, correct me if I am wrong.

Thought experimet:
Considering you always want the same acuity of your game and you have 4 objects that take the exact same amount of UV space but have different textures.

Then there would be a perfect spot between texture size and number of objects that share the same texture considering your goal is best performance.
In this case there would be 4 possibilities:

1 texture where all objects share the same one
2 texture for two of the objects
3 texures where it would be a mix of those above
or 4 textures where every object have their own

If performance is your main goal then there would be only one variable to change depending on how acuit you want your game, the acuity, wouldnt it?

Hope you understood my thoughts^^


texts: What's wrong with reversing an action like this?

texts:
I'm working on an undo and redo system map editor and have come across a major issue. If I place a tile down, move right a tile, and then move back to that tile I previously placed everything works fine. Until I try and Undo, Redo, and then Undo again.

This is the state when they're placed:

Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:

The undo redo stack looks something like:

Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
41
Unexecuting:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Executing:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Unexecuting:
X: 1
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
-1
Unexecuting:
X: 0
Y: 0
Tiles: {X:32 Y:160 Width:32 Height:32}
Previous Tiles:
41

I don't want this to be a code dump or "debug my code for me". I understand the problem is located at the bottom most segment where it assigns the tile an ID of 41 once again - since that's what it's previous value was. This works the first time - but not the second as seen. I'm confused to why the algorithm fails. If anyone has written something similar, feedback would be appreciated. I don't need code-fixed - just hints as to where I can find a working algorithim or a rational explanationa s to why this happens. It's just a simple pencil tool that should write tiles the grid.

  public new void Execute(GameMap gameMap)
{
    Console.WriteLine("Executing: ");
    PrintState();

    _previousTiles.Clear();

    // Get vertical portion
    var curTexture = MapEditorGlobals.CurrentActiveTexture;

    // We need to loop over the width of the editor
    for (int w = 0; w < SelectedTiles.Width / 32; w++)
    {
        for (int h = 0; h < SelectedTiles.Height / 32; h++)
        {

            var gX = SelectedTiles.X / 32 + w;
            var gY = SelectedTiles.Y / 32 + h;

            var tY = (gY) * curTexture.Width / 32;
            var tX = gX;
            var tileID = tY + tX;

            _previousTiles.Add(gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId);
            gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId = tileID;
        }
    }

}

  public new void UnExecute(GameMap gameMap)
        {

            Console.WriteLine("Unexecuting: ");
            PrintState();

            List<int> newTiles = new List<int>();

            // Get vertical portion
            var curTexture = MapEditorGlobals.CurrentActiveTexture;

            // We need to loop over the width of the editor
            for (int w = 0; w < SelectedTiles.Width / 32; w++)
            {
                for (int h = 0; h < SelectedTiles.Height / 32; h++)
                {

                    var gX = SelectedTiles.X / 32 + w;
                    var gY = SelectedTiles.Y / 32 + h;

                    var tY = (gY) * curTexture.Width / 32;
                    var tX = gX;
                    var tileID = tY + tX;

                    newTiles.Add(gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId);
                    gameMap.Layers[Layer].MapTiles[X + w][Y + h].TileId = _previousTiles.Last();
                    _previousTiles.Remove(_previousTiles.Last());
                }
            }

        }


texts: Capture High Resolution Screen Shot for Unity Game

texts: I'm working on a mobile game. We need some HD screen shot to use in our press kit. I'd like to know, how do we capture HD screen shot of games inside unity's editor. Resolution must support printing quality of banners that we would use to showcase our game in local game expo.


texts: how to load normals for a model from texture2d?

texts:
I know i can do this through custom shaders, but i want to know is it possible to set it through xna itself. As for each effect i have pick normals from a texture2d, i want to change normals of model.

I have done this much, but i don't know how to go further??

  foreach (ModelMesh mesh in Home.Model.Meshes)
       {
           if (mesh.Name == meshName)
           {
               foreach (ModelMeshPart part in mesh.MeshParts)
               {
                   VertexPositionNormalTexture[] normals = new VertexPositionNormalTexture[part.VertexBuffer.VertexCount];
                   part.VertexBuffer.GetData<VertexPositionNormalTexture>(normals);

                   Color[] data = new Color[normalMap.Height * normalMap.Width];
                   normalMap.GetData<Color>(data);
               }
           }

       }

Thank you


texts: How to generate tiled delaunay triangulation mesh (delaunay triangulation within a rectangle with triangles connecting opposing edges)?

texts:
I have a nice triangulation of a square mesh. The way I do this currently is

generate square mesh (two triangles), from (0.,0.) to (1.,1.) (axis-aligned and normalized for simplicity)
add point somewhere within square (poisson disk sampling)
detect which triangle point falls within
subdivide into 3 triangles
iterate over all tris, perform "delaunay flips" where necessary
GOTO 2

This works great (a bit simplified, as there's also edge-case detection code to account for colinear points, fp precision errors, etc...).

Anyways, what I want to do now is have the edges of this square "wrap".

EDIT:
Upon request, here are some illustrations to help convey my problem:

So, we have an initial set of pts:

A normal delaunay triangulation would generate something like this:

What I want is a tessalated delaunay triangulation. That is, what edges would have to exist to allow this to be infinitely tile-able:

An example set of edges might be like this:

Now, imagine if you left those connections, but didn't tile them. I've drawn just the "wrapping" connections for the red dot and the purple dot in green, assuming there is only one instance of each dot in view (centered around the initially displayed set of dots):

Already, it's a topological mess. But in theory, I'd expect it would work, assuming I stick to some implementation constraints.

So, the plan would be to create a mesh containing all these pts and their respective connections. I would have some offset, and move the points in the vertex shader as a modulus of that offset. That way, every point will exist as "the closest instance of that point in the infinitely tiling plane" to the offset (for example, the camera). Since all the connections are in place, I wouldn't have to mess with them, and would get infinitely-scrolling (repeating) "terrain". All the topologically-messy-wrapping connections would be "backfacing" triangles, and would be culled... right?

Edit: Ok no they would not necessarily be backfacing... shoot. (if the wrap of the triangle was both vertically and horizontally wrapped, it would be back to frontfacing. My best guess at a solution is to, in the vert shader, artificially lower all the pts "close" to being wrapped, so any wonky giant tri's show up way below any legitimate tris. #hack.

Ok. off to try this. Will report back with any updates...