texts: Keep track of VoxelData/NPC in parallel Level

texts:
Background

I'm tring to make a First-Person-Shooter Game in a Voxel-World (Finit Size) with Unity3d.

The Player has some kind of a Base that he has to protect against Enemy units. There are also one or more enemy Bases that the Player has to destroy, but in a different Level/Map.

The Game has multiple Levels that are connected through predefined Ports. So the Player and other Units can travel from Level to Level. There are a couple of Levels to explore. (Maybe there could be infinit Levels in the future.)

At game start I create a LevelManager and all Levels as Children of them. They can spawn an manage the Units and Voxel-Blocks independently. One ChunkManager renders always the current Level where the Player is in. He creates multiple Chunks which itself generate the Mesh from the current Voxel-Data of the Level. This works all very well and I'm also able to travel between the Levels. (This runs all in one Scene.)

At the moment I try to implement some kind of a Worm unit. They spawn from time to time anywhere in each level and can move randomly around and modify the Voxel-World by eating the Blocks away... type of random enviroment event.

Problem

The problem I can't solve is how to simulate all the Worms in parallel Levels? And the Blocks they have eaten? Same problem would occur for the enemy bases if they grow and build new defences and so on.
Because when the Player enter a Level there should be some differences since his last visit.

My attempt

All my Units and Buildings have already separated logic and rendering components. So they can work properly even when not rendered by the ChunkManager. Its working for maybe 3 Levels and a handfull of worms but if I increase the amount of Levels it gets starting to go laggy (4-10FPS). So this would not be the right way to go or is it and my code is crap?

Has someone any suggestions for me how I can solve this?

Edit

I disable now all none active Levels and reactivate always the current Level where the Player is in. So I can better manage the objects that realy need computation time.

The problem I get now is how can I simulate the progress in a Level since start? Example for the worm unit. He would have moved across the Level and left a path of removed voxels. Should I made a seperate method to calculate the path that would be made or the last X minutes or should I just call the Update method multipletimes to match the missed calls since last X minutes? This should then be made by all Objects that can modify the Level or produce something.


texts: Help on 'varying' and 'uniform' keywords in GLSL (OpenGL 4+)

texts:
I want to use a shader just for learning purposes but I have a few questions about it.

I have the following code:

Vertext shader:

const float Eta = 0.66;         // Ratio of indices of refraction
const float FresnelPower = 5.0;

const float F  = ((1.0-Eta) * (1.0-Eta)) / ((1.0+Eta) * (1.0+Eta));

varying vec3  Reflect;
varying vec3  Refract;
varying float Ratio;

void main()
{
    vec4 ecPosition  = gl_ModelViewMatrix * gl_Vertex;
    vec3 ecPosition3 = ecPosition.xyz / ecPosition.w;

    vec3 i = normalize(ecPosition3);
    vec3 n = normalize(gl_NormalMatrix * gl_Normal);

    Ratio   = F + (1.0 - F) * pow((1.0 - dot(-i, n)), FresnelPower);

    Refract = refract(i, n, Eta);
    Refract = vec3(gl_TextureMatrix[0] * vec4(Refract, 1.0));

    Reflect = reflect(i, n);
    Reflect = vec3(gl_TextureMatrix[0] * vec4(Reflect, 1.0));

    gl_Position = ftransform();
}

Fragment shader:

varying vec3  Reflect;
varying vec3  Refract;
varying float Ratio;

uniform samplerCube Cubemap;

void main()
{
    vec3 refractColor = vec3(textureCube(Cubemap, Refract));
    vec3 reflectColor = vec3(textureCube(Cubemap, Reflect));

    vec3 color   = mix(refractColor, reflectColor, Ratio);

    gl_FragColor = vec4(color, 1.0);
}

First thing I notice is the varying keyword. I couldn't really find out if this is deprecated or not. I'm using OpenGL 4+. So shouldn't that be changed to in or out?

Other thing is the uniform keyword. That means I have to pass a value from my code to my shader right? In this case I have to pass a cubemap. I guess I can figure out how to create one of those later, that's not important right now. But what I do like to know is how to change the value of the variable. I couldn't really find any info about that.


texts: Integrating Scene Graphs and Physics Engines

texts:
For some specific reasons, i will have to use a graphic engine based on Scene Graphics with a Physic Engine without this concept.
I was thinking about a clear way to integrate both representation but ... i did not found something that convinces me.

The problem that always appears is that the scene graph is a hierarchical structure and the Physical engine is not.
The position of a node in a scene graph depends of its parents, and when the parents changes its location, the son must be updated, but the son can be physically simulated (its position is always in global coordinates) ...

(there are lots of others situations similar to this ... - hard to calculate relative positions/orientations and keep both worlds in sync)

The only way i found is to have all the physically simulated objects as direct sons of the root node of the scene graph (no relative positions at all)
In the physically simulated nodes, we dont propagate relative positions/orientations, each of this nodes only store world positions/orientations, not relatives.
But this constraint sounds a little to much and probably will kill (a bit =P) some of
beneficts of scene graph like cullings. (after all, most of my scene wont follow any hierarchy ... )

how people usually solve this kind of situations ?


texts: How does the Maya ASCII FBX format store positions within animation?

texts:
I want to understand Maya's ASCII FBX format so I can convert animations in it to OSG (OpenSceneGraph) format.

I have a simple sphere, with a translation in one direction for 30 frames baked into an animation. I was expecting to see a list of values like this:

Frame #, X-position, Y-position, Z-position

However, I find nothing like it in the output file. For example, at frame 1, X/Y/Z = -7.189/0/10.136, but I cannot find any of these, or any other X/Y/Z position anywhere in the file.

What am I missing?

Could someone point out the frame/xyz position in the file?


texts: How do I create a color picker with variable hue and saturation?

texts:
I am trying to create a Color Picker similar to that of MS Paint.

Unfortunately, I can't figure out the algorithm for saturation.

This is what my current algorithm creates.
Anytime I try to perform a saturated effect going down on the Y axis, it just makes everything after the first line completely red or black.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML;
using SFML.Graphics;
using SFML.Window;

namespace Source
{
class ColorWheel : IGameObject
{
    Image image = new Image(255*6,355);
    Color color = new Color(255,0,0);
    int brightness = 255;
    public Sprite sprite = new Sprite();

    public ColorWheel()
    {
        for (int y = 0; y < 255; y++)
        {
            for (int x = 0; x < 255 * 6; x++)
            {
                //Red 255 - Green 0-254
                if (color.R == brightness && color.G < brightness && color.B == 0)
                {
                    color.G += 1;

                    //color.R -= (byte)y;
                    //color.G += (byte)y;
                    //color.B += (byte)y;
                }
                //Green 255 - Red 255-0
                else if (color.R > 0 && color.G == brightness && color.B == 0)
                {
                    color.R -= 1;

                    //color.R -= (byte)y;
                    //color.G -= (byte)y;
                    //color.B += (byte)y;
                }
                //Green 255 - Blue 0-255
                else if (color.R == 0 && color.G == brightness && color.B < brightness)
                {
                    color.B += 1;

                    //color.R += (byte)y;
                    //color.G -= (byte)y;
                    //color.B += (byte)y;
                }
                //Blue 255 - Green 255-0
                else if (color.R == 0 && color.G > 0 && color.B == brightness)
                {
                    color.G -= 1;

                    //color.R += (byte)y;
                    //color.G -= (byte)y;
                    //color.B -= (byte)y;
                }
                //Blue 255 - Red 0-255
                else if (color.R < brightness && color.G == 0 && color.B == brightness)
                {
                    color.R += 1;

                    //color.R += (byte)y;
                    //color.G += (byte)y;
                    //color.B -= (byte)y;
                }
                //Red 255 - Blue 255-0
                else if (color.R == brightness && color.G == 0 && color.B > 0)
                {
                    color.B -= 1;

                    //color.R -= (byte)y;
                    //color.G += (byte)y;
                    //color.B -= (byte)y;
                }

                image.SetPixel((uint)x, (uint)y, color);
            }

                //brightness--;
        }

        Texture texture = new Texture(image);
        sprite.Texture = texture;
    }

    public void Update(double dt)
    {
    }

    public void Render(RenderWindow rWindow)
    {
        rWindow.Draw(sprite);
    }

}

}


texts: error in post a screen shot of game scores with Android Intent in LIbgdx game

texts:
I want to post a screen shot of my game on social apps. I have developed this game using Libgdx framework. I have created an interface in Core class.
Here is its Intent share specific code.

public interface ActionResolver {
   public void shareit();

   }

then on my Androidlauncher class I implement it

public class AndroidLauncher extends AndroidApplication implements
        ActionResolver{ .......

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

gameView = initializeForView(new MainGame(this),
                new AndroidApplicationConfiguration());// View
}

 @Override public void shareScreen() {

      String message = "Text I want to share."; Intent share = new
     Intent(Intent.ACTION_SEND); share.setType("text/plain");
      share.putExtra(Intent.EXTRA_TEXT, message);

      startActivity(Intent.createChooser(share,
      "Title of the dialog the system will open"));

      }

     public void createIntent(View v){

      { // View view =gameView.getRootView(); Bitmap icon =
      getBitmapFromView(v.getRootView()); Intent share = new
      Intent(Intent.ACTION_SEND); share.setType("image/jpeg");

      ContentValues values = new ContentValues();
      values.put(MediaStore.Images.Media.TITLE, "title");
      values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri =
      getContentResolver().insert(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

      OutputStream outstream;

      try { outstream = getContentResolver().openOutputStream(uri);
      icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
      outstream.close(); } catch (Exception e) {
      System.err.println(e.toString()); }

      share.putExtra(Intent.EXTRA_STREAM, uri);
      startActivity(Intent.createChooser(share, "Share Image")); } }

public void createIntent(View v){

      Bitmap icon = getBitmapFromView(v.getRootView()); Intent share = new
      Intent(Intent.ACTION_SEND); share.setType("image/jpeg");

      ContentValues values = new ContentValues();
      values.put(MediaStore.Images.Media.TITLE, "title");
      values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri =
      getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      values);

}
public static Bitmap getBitmapFromView(View view) {

        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),
                view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return returnedBitmap;
    }

I also Initialize my Interface in MainGame class

public MainGame(ActionResolver actionResolver) {
        super();
        this.actionResolver = actionResolver;

One thing I am confuse Which view I should pass to start this intent? becuase its libgdx framework.
Secondly on Android side obviously Canvas, Bitmap all would be from Android.

with this whole code I am able to start my intent but when i share screen the screen is just a black screen. but That screen has an ad appears on its bottom that I am already using through admob.

I have searched it here a lot, found related thread of sharing a black screen instead of actual screen shot of game. but I dont Understand all that because some asking to use some different library. I dont wana use any external library nor facebook sdk for facebook. I just want simple android Intent to share Screen . Kindly help me out.


texts: How do I move the camera in 2D LWJGL openGL?

texts:
I am making a top-down rpg game with the LWJGL but I can't figure out how to make the camera follow the player. I've tryed using GLU.gluLookAt() but it seems to be designed for 3D and when I try it with my game everything currently on the screen disappears. I have no idea where the camera gets moved to. Please explain simply how to use GLU.gluLookAt() or a better alternative to move the camera.

public class Camera {

    public float x = 0;
    public float y = 0;

    public void moveCamera(float toX, float toY){
    GLU.gluLookAt(x+toX, y+toY, 0.0f, 0.0f, 0.0f, 0.0f, 0f, 1f, 0f);
    }
}


texts: How do I make a flickering engine exhaust animation using only bone animation?

texts:
I'm trying to replicate the flickering engine exhaust animation in this SketchFab model.  SketchFab doesn't support particle systems, so the animation must be a simple bone animation.

Can someone help me understand how to achieve such an effect?

My best guess is animated opacity, but I don’t know how to replicate it.
My final goal is to use it in a Unity 5 mobile game.


texts:
So far I've tried Bluetooth but it doesn't appear to work on either windows or Ubuntu (for this use-case; it can connect to printers fine). I've also looked up USB-bridge-cables, but from what I’ve read so far, they can't be used for this, either.

Since the game is a hobby-project, the solution can neither be expensive, nor require months of work. It's a turn-based game. Otherwise I wouldn't be asking but finding a different project after finding out neither Unity nor Unreal Engine can do this; currently, I'm using neither.

Is there a way to do local multiplayer on a combination of Windows/Ubuntu computers?


texts:
I've got a problem when loading objects using assimp. I did succesfully load vertex data and I am able to draw static mesh (without bones and animations, I've got few bugs there but I'll go back to solving that problem after I solve this one). Back to the problem. I have loaded texture coords using this code

tmp.Tex.x = modelScene->mMeshes[i]->mTextureCoords[0][j].x;
tmp.Tex.y = modelScene->mMeshes[i]->mTextureCoords[0][j].y;

of course it is in cycle for all meshes and all vertices (i, j respectively).

Then I draw it using DirectX 11 and I get this result:

I tried almost all permutations of post loading flags that had something to do with UV coordinates and nothing helped (only the yellow spots changed it's color to green in some cases).

Textures should be loaded correctly (I checked file names in debugger and they were correct) then I loaded it using directX functions for that so no problems should not there.

The code for drawing is basically the same as in the book from Frank Luna, with minor changes (because I redesigned the whole framework to my needs). Shader is whole from the book.

I am hopeless already. I am looking for working way to load my models (fbx, dae) to my demo for almost 2 months now and nothing worked (this is the closest I've got), so if anyone have seen anything similar I would be really grateful for any pointers on where to look for problem.

Here is the source image

EDIT 1:
So I tried to draw the texture on the quad using the same shader I use for drawing on model and somehow I used wrong TangentU and Normals what resulted in the picture on quad being black with occasional (when I moved camera) white stripes with shades of the actual texture so can't this problem have anything to do with tangents or normals? Or maybe something with TangentU being something different than actual Tangent?
Code I use to load those is:

tmp.Normal.x = modelScene->mMeshes[i]->mNormals[j].x;
tmp.Normal.y = modelScene->mMeshes[i]->mNormals[j].y;
tmp.Normal.z = modelScene->mMeshes[i]->mNormals[j].z;

tmp.TangentU.x = modelScene->mMeshes[i]->mTangents[j].x;
tmp.TangentU.y = modelScene->mMeshes[i]->mTangents[j].y;
tmp.TangentU.z = modelScene->mMeshes[i]->mTangents[j].z;


texts: Rigidbody slows down when its going up a slope. What can I do?

texts:
I am using unity and I am creating a 3d topdown game. There is no jump feature. The input handling supports only x and z axis player movement. Climbing slopes or  falling from gaps is something I want to happen without certain input.

So,
I have a rigidbody which I move by directly setting its velocity. When it goes up a slope it slows down.

I would like it to keep the same speed.

Now I do it like this:

    void Update(){
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
}

void FixedUpdate(){

MyRB.velocity = moveInput.normalized * runSpeed
}

I am using a capsule collider on the rigidbody and a box collider for the slope. The physics materials of the colliders are the default/none (not changed).


texts: 360+ degree rotation skips back to 0 degrees when using Math.Atan2(y, x)

texts:
I'm new to XNA and this is my first actual project, so forgive my noobness.

I'm using

 jointAngle = System.Math.Atan2(RightStick.Y, RightStick.X);

in order to set an angle of a joint (farseer) so that the attached body points in the direction pushed with the right joystick. This all works great and i get values from negative pi to pi which correlate with the pushed direction. The problem arises when i go from 360 degrees to 361. Instead of the continued rotation beyond 360 degrees that one might expect, it jumps back to 0 degrees (or -3.14 radians), which causes a jerking motion as the joint suddenly shifts 359 degrees back instead of 1 forward.

Is there a simple way to account for this? I came up with a few solutions, but they're all pretty messy at best and completely unreliable at worst.

Please help!


texts: 2d side scroller slope physics and collisions

texts:
In old 2d games such as double dragon, streets of rage etc. where the player could move “up and down” on the y-axis to give an illusion of depth (as opposed to something like Mario) how were slopes and stairs handled along different points on the y-axis to give the appearance of still moving in a straight line?

For instance in the above picture would you set collision masks where the green lines are? Then imagine the characters are the red and blue lines respectively, how would you handle them in effect being moved “down” by gravity when in fact there isn’t really any gravity? For the top line I assumed when it hit the green line, rather then stopping or bouncing back on the x-axis you’d just nudge them down and continue the x movement?

I understand how this could be completed in 3D but I’m perplexed how this would’ve been achieved in purely 2d environments. Or maybe I’m imagining slopes/stairs in these old games...

I’m working in SpriteKit, so any ideas specific to that would be great but just understanding how this was accomplished theoretically in the first instance would be great.

Thanks

edit - after some thinking I don't think my 'collision' theory would work going down the slope for the blue line as it wouldn't be colliding unless it came off it's "straight" path, and also the problem would be reversed when going 'up' the slope.

so for instance in the above image where the characters are moving up the slope the other way I'm curious how this would have been handled? My thoughts now are, would the darker grey area with the "1" on it, actually be an entire entity itself or a collision mask? You'd then work out based on the characters "Y entry" point on to it (either at the top or the bottom) and based on their direction, where their 'Y' point should then be?


texts: unity 3d mouselook script help, weird issue

texts:
I'm coming back to Unity after a year or two of busy college and I'm having to relearn everything I've forgotten. One thing I cant seem to get right is this basic mouselook script I wrote. Here is the code:

    float x;
    float y;
    public float sensitivity = 75.0f;
    public float maxVerticalAngle = 75.0f;
    public Rigidbody Character;

    void Awake()
    {
        Vector3 euler = transform.rotation.eulerAngles;
        x = euler.x;
        y = euler.y;
    }

    // Update is called once per frame
    void Update()
    {
        x += Input.GetAxis("Mouse Y") * (sensitivity * Time.deltaTime);
        y += Input.GetAxis("Mouse X") * (sensitivity * Time.deltaTime);
        x = Mathf.Clamp(x, -maxVerticalAngle, maxVerticalAngle);

        //apply this just to the camera and it works
        transform.rotation = Quaternion.Euler(-x, y, 0.0f);

        //apply x changes to camera and y changes to parent rigidbody capsule and it no longer works correctly
        transform.rotation = Quaternion.Euler(-x, 0.0f, 0.0f);
        Character.transform.rotation = Quaternion.Euler(0.0f,y,0.0f);
    }

Okay, now at the end is where my problem occurs. Let me explain a little: if I apply the quaternion with both x and y changes to the rotation then it works smoothly and the camera rotates on both axes. If, however, I apply the change in x to the camera to allow looking up and down, and I apply the change in y to the rigidbody capsule I have as a parent to the camera the script is attached to then I get a weird problem. The camera rotates up and down smoothly, but the capsule twitches and only rotates a few degrees. If, however, I comment out the line where I apply changes to the camera rotation then the parent capsule rotates normally now.

TL;DR
Camera is child to a capsule.
When applying rotational changes to the camera and rigidbody one line after the other, the camera rotates fine, but the rigidbody does not. If I comment out the camera's rotation changes then the rigidbody rotates fine again.

I think the problem may be that I'm rotating a parent object to the camera and I'm using mouse movement to rotate the rigidbody. I'm unsure though. Please help.

If you want to recreate what I've done, then child a camera to a capsule and apply the script. Add the capsule to the rigidbody in the script and comment out this:

//apply this just to the camera and it works
transform.rotation = Quaternion.Euler(-x, y, 0.0f);

Edit: Thank you for the help. If you need more info, then please ask!


texts: How can I get N random objects from array?

texts:
[Range(5, 50)]
    public int waypointsCount = 10;

    private System.Random random = new System.Random();

    // Use this for initialization
    void Start ()
    {
        var Nodes = UnityEngine.GameObject.FindGameObjectsWithTag("Node");
    }

I want to get a random number of gameobjects from Nodes according to the number in waypointsCount. So if for example the number is 10 then I want to get 10 random gameobjects from the array nodes. And the gameobjects should not be duplicates.


texts:
I know this question has been asked a lot of times, and I have tried the solutions that were provided and I still have no valuable result, so I thought...maybe a new set of eyes could help.

I have a game in which the player can navigate around the scene environment using a virtual joystick and look around the scene by scrolling through the screen(like it is seen in most mobile fps games).

The problem that I am having now is that my "look around" script allows touch inputs to pass through UI elements on mobile, but everything works fine on the editor.

Useful tips:

1) I am using Unity 2019.3.0f5

2) I setup the script to work with Cinemachine Free Look, and my script(seen below) is attached to it.

Here is my code:

using UnityEngine.EventSystems;
using UnityEngine;
using Cinemachine;

public class CinemachineCoreInputTouchAxis : MonoBehaviour
{
private readonly float TouchSensitivity_x = 10f;
private readonly float TouchSensitivity_y = 10f;

[SerializeField] private bool UseTouchControls = true;

private static int Index = 0;

void Start()
{
    if(UseTouchControls)
        CinemachineCore.GetInputAxis = HandleAxisInputDelegate;
}

private float HandleAxisInputDelegate(string axisName)
{
    switch (axisName)
    {
        case "Mouse X":
            if (Input.touchCount > 0 && !IsPointerOverUIObject())
                return Input.touches[Index].deltaPosition.x / TouchSensitivity_x;
            else
                return Input.GetAxis(axisName);
        case "Mouse Y":
            if (Input.touchCount > 0 && !IsPointerOverUIObject())
                return Input.touches[Index].deltaPosition.y / TouchSensitivity_y;
            else
                return Input.GetAxis(axisName);
        default:
            Debug.LogError("Input <" + axisName + "> not recognized.", this);
            break;
    }
    return 0f;
}

public static bool IsPointerOverUIObject()      //Called to check if the pointer is over a ui object
{
    bool value = false;
    for (int i = 0; i < Input.touches.Length; i++)
    {
        Index = i;
        value = EventSystem.current.IsPointerOverGameObject(Input.GetTouch(Index).fingerId);
        if (value)
            break;
    }
    return value;
}
}

Can anyone please let me know what I am failing to see and how to fix it?


texts: Shuffle tiles position in the beginning of the game XNA Csharp

texts:
I'm trying to create a puzzle game where you move tiles to certain positions to make a whole image. I need  help with randomizing the tiles start position so that they don't create the whole image at the beginning. There is also something wrong with my offset, that's why it's set to (0,0). I know my code is not good, but I'm just starting to learn.

My start-up tile positioning code

        spriteBatch = new SpriteBatch(GraphicsDevice);
        PictureTexture = Content.Load<Texture2D>(@"Images/bildgraff");
        FrameTexture = Content.Load<Texture2D>(@"Images/framer");

        //Laddar in varje liten bild av den stora bilden i en array

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {

                Vector2 position = new Vector2(x * pictureWidth, y * pictureHeight);

                position = position + Offset;

                Rectangle square = new Rectangle(x  * pictureWidth, y * pictureHeight, pictureWidth, pictureHeight);

                Square frame = new Square(position, PictureTexture, square, Offset, index);
                squareArray[x, y] = frame;

                index++;
            }
        }

For reference, here is the square class:

class Square
{

    public Vector2 position;
    public Texture2D grafTexture;
    public Rectangle square;
    public Vector2 offset;
    public int index;

    public Square(Vector2 position, Texture2D grafTexture, Rectangle square, Vector2 offset, int index)
    {
        this.position = position;
        this.grafTexture = grafTexture;
        this.square = square;
        this.offset = offset;
        this.index = index;
    }

    public void Draw(SpriteBatch spritebatch)
    {
        spritebatch.Draw(grafTexture, position, square, Color.White);
    }

    public void RandomPosition() {  }

    public void Swap(Vector2 Goal )
    {
        if (Goal.X > position.X)
        {
             position.X = position.X + 144;
        }
        else if (Goal.X < position.X)
        {
            position.X = position.X - 144;
        }
        else if (Goal.Y < position.Y)
        {
            position.Y = position.Y - 95;
        }
        else  if (Goal.Y > position.Y)
        {
            position.Y = position.Y + 95;
        }
    }
}


texts: generating random block-based worlds with 3D noise

texts:
I want to create a 3D block-based infinite world.

For any block, I want to be able to compute its block type.

3D perlin noise is the usual building block of such a world.  If you ask the 3D noise function the value for a 3D point, it'll give you a value between -1 and 1.

How do you turn this number into a block type?

I want blocks on the surface to be turf, and different minerals to have different probabilities based on depth.  I want sprawling caves and caverns and lava flows but not small ones.  And so on.

So how do you turn noise into block types into a coherent subterranean world?  Particularly how do you make things like coal appear in seams and crystals only appear in caves and any other rules that can be invented that make the type of a block dependent upon its neighbours?

And how to do this efficiently, in an oracle function rather than by having to create large 3D arrays to store the decided outcomes of some terraforming?


texts: Maya - Rotate an object around it's pivot point by snapping a vertex to another object's point

texts:
The title of the question maybe a bit confusing, so I'll try to make it clear. I have the object (A - finger) and I want to align rotation of another object (B - nail)  to a specific edge on the surface of the object A. So I set the pivot point of the object B to it's approximate central vertex and afterwards snapped the whole object B to vertex of the object A, but I don't know how rotate the object B like on the image below.

I know how to accomplish that in Blender, but not in Maya.


texts: Scaling a rotated rectangle in a given direction

texts:
I'm facing an issue when trying to scale a rotated rectangle in a given direction.

In my context, the width and height of the rectangle are based on the texture size multiplied by a scale factor (one for X-horizontal and another for Y-vertical).

Basically, if a texture width is 100 and the scale-X factor is "2" the calculated width is 200, which is the double. The same goes for the height.

Right now, if I want to scale the rectangle to the left, I'm applying a scale value and at the same time I'm modifying the X position to compensate the increased scale factor (to keep the right side of the rectangle in the same position).

If there is no rotation applied, this method works nicely, but things complicate when I rotate the rectangle (in the following example 45º):

From what I'm understanding, this time I have to compensate the Y position as well because of the slope BUT I can't figure out the correct relation to apply an acceptable value.

Any ideas? Thanks!


texts: How to detect 2D line on line collision?

texts:
I'm a flash actionscript game developer who is a bit backward with mathematics, though I find physics both interesting and cool.

For reference this is a similar game to the one I'm making: Untangled flash game

I have made this untangled game almost to full completion of logic. But, when two lines intersect, I need those intersected or 'tangled' lines to show a different color; red.

It would be really kind of you people if you could suggest an algorithm for detecting line segment collisions.
I'm basically a person who likes to think 'visually' than 'arithmetically' :)

Edit: I'd like to add a few diagrams to make convey the idea more clearly

P.S I'm trying to make a function as

private function isIntersecting(A:Point, B:Point, C:Point, D:Point):Boolean

Thanks in advance.


texts: interace between C and Lua function with 3D vector arguments

texts:
I have C++ function (which runs some physical simulation inside my game engine) which looks like this:

void doSomePhysics( int nIters, Vec3d pos, Vec3d vel ){ /*... don't care ...*/ }

I want call this function from a lua script likes this:

doSomePhysics( 100, {1.0,-2.0,3.0}, {-8.0,7.0,-6.0} )

I'm trying to figure out how to make lua interface to this function.

I would like to do several general helper functions for passing 2D,3D and 4D vectors and matrices since I will heavily use them.

Here is sketch what I'm currently trying to do (But I know it is not correct):

void lua_getVec3(lua_State *L, Vec3d& vec ){
    // universal helper function to get Vec3 function argument from Lua to C++ function
    luaL_checktype(L, 1, LUA_TTABLE);
    lua_settop(L, 1);
    int a_size = lua_rawlen(L, 1);
    lua_rawgeti(L, 1, 1); vec.x = lua_tonumber(L, -1);
    lua_rawgeti(L, 2, 2); vec.y = lua_tonumber(L, -2);
    lua_rawgeti(L, 3, 3); vec.z = lua_tonumber(L, -3);
    lua_pop(L, 3);
}

int l_doSomePhysics(lua_State* L){
    // lua interface for doSomePhysics
    Vec3d pos,vel;
    int n = lua_tointeger(L, 1);
    lua_getVec3(L, pos );
    lua_getVec3(L, vel );
    doSomePhysics(n,pos,vel);
    lua_pushnumber(state, 123);
    return 1;
}

I read several short tutorials 1 2 3 but it seems horribly complicated, confusing and error-prone ... I'm completely lost in stack indexes (what is my current position in the stack?, what is correct relative index? etc.). I'm reluctant to believe the most famous game scripting language needs sooooo much boiler-plate code and so much pain for interfacing every little function.

EDIT: answer is here


texts: How to check if all switch objects in a room are set to true?

texts:
I'm trying to implement a puzzle mechanic in Game Maker Studio 2.
Where you need to activate multiple switches for an event to happen (e.g. opening a door)

However, I'm currently stuck in recieving the booleans from all switch objects in a room. Currently It's only working when any (or only the first) switch is hit.

Here's an example of how it works:

Switch collision with projectile:

switched = !switched

'Switchdoor' step event:

if (switch.switched == true) //this only seem te register the first switch placed
{
    //do action
}

If I've used XNA, I could make a List<> to store all the rendered switches and get their boolean values. But what can I use instead in Game Maker Studio 2, who works with rooms?


texts: How can I derive hierarchical draw ordering for entities in an entity system?

texts:
How do you implement hierarchical render order in an entity system?

For example: two player entities each carry a gun entity. If you set the player entities to zindex = 0 and the gun entities to zindex = 1, then player 1 might render behind player 2 but his gun will render in front of player two.

I'm migrating a game from a scene-graph system where the order is self-evident from the parent/child relationship. The only way I can see of achieving the above is to simulate that parent/child relationship by giving every entity its own reserved range of z-indexes like so.
player1 z=0
player1-gun z=1
...
player2 z=5
player2-gun z=6

This would require some kind of auto assignment system. Is this how it's done or is there some pattern I'm missing?


texts: How can I create a heightmap for ocean surface simulation?

texts:
I am working on a game that is based on boats fighiting each other. The game is finished but due to some license incopatibilities, I have to change how I simulate the surface of the sea.
What I used until now was a mesh with all the vertices of the sea, and I was setting each vertex's height using FFT (with a library that is the one I can't use). Now I don't have time to port it to another FFT library, so do you know any sine / cosine based formula or any other "easy" method that I can use to compute the height of each vertex which also keeps consistency between frames?
Having the game finished I need to keep some features of the previous implementation like it has to be CPU computed because the sea surface is affecting the boat's rotation.


texts: How to get struct layouts from vertex shader input using ID3D12Reflection

texts:
I am attempting to write a code generator that builds C++ structs/classes from D3D12 reflection data built using DXC. Given a simple vertex shader signature:
struct Light
{
    float3 Color;
    float3 Dir;
};

struct cbPerPass : register(b0)
{
    float4x4 gWorldProjTransform;
    Light gGlobaLight;
};

struct VertexIn
{
    float3 Pos      : POSITION;
    float4 Color    : COLOR;
};

struct VertexOut;  // unimportant for the question

VertexOut VS(VertexIn vin) { // do calculations here }

I can retrieve the input parameters via ID3D12ShaderReflection::GetInputParameterDesc(), but this only reports the mapping of VertexIn members to shader registers and any attached semantics. I can get the layout of cbPerPass through ID3D12ShaderReflection::GetConstantBufferByIndex() and the layout of Light through the ID3D12ShaderReflectionType interface.
However, what I would like to retrieve is the layout of the VertexIn struct. Is there a way to do this?


texts: Authentication between client, central server, and player ran server

texts:
I am developing an open source game that uses a client-server scheme similar to Minecraft. We will control the central authentication server that verifies an account is valid, while players will run their own servers.

Authenticating the client is simple, but how can the server know that the user is valid, without having any access to is credentials or session token?

For example:

Client > Auth Server: Sends user credentials.
Auth Server > Client: Responds with a session ID if valid login.

Then, the client can connect to the server, but the server has no way of verifying is the client is who it says. These servers are ran by players, which make it easy for them to modify the server and collect the user data. (Only the central auth server can be trusted)

The authentication server could accept TCP connections, but I wonder if HTTPS would be easier in this case, as getting a response is easier than establishing a listener on each side, especially for only a few requests.


texts: What is the difference between libraries like C++/PDCurses and SFML?

texts:
I have read that PDCurses is a library that can be used to create 2D games however SFML is also a library but they are not in the same category I presume according to what I have read:
"The system terminal is a part of your operating system which allows communicating with the computer using text. If you choose to do this, it is also a good idea to use a library — but now, you use a library for creating programs working in the terminal, rather than a game library. Here, the most popular choice is Curses"
Can somebody explain the difference?


texts:
I've been an android developer for a while and am thinking about getting into gaming. While looking for a game dev framework, I thought libgdx provides very friendly documentation and functionality. So I would like to use it if there is no big obstacle.

But when I tried to see how many developers employ this library, I could find not that many. Is there anything wrong with this library? In other words, I would like to know its advantages or disadvantages from any experienced developer.

UPDATE: After reviewing its documentations and trying to build simple games with libgdx, I decided to go with it as its documentations are good enough and its community is very active. What I liked the most is that it provides a bunch of demo games that I can learn a lot from.


texts: How to implement the missile trajectories in the classic missile command game - pygame

texts:
I am doing a clone of the classic arcade game missile command, i am curious about how to implement the trajectories of the missiles. I have a solution that looks pretty similar to the original game, but it have some problems that i don't know how to avoid.
Here is the relevant code i have right know:
missiles_attack = []

class Missile(object):

    def __init__(self, pos_src, pos_dst, color, speed):

        # direction of the missile
        direction = (pos_dst - pos_src).normalize()

        # total distance that missile must travel to reach his target
        self.__distance = pos_dst.distance_to(pos_src)

        # the current distance traveled
        self.__distance_traveled = 0

        # how many the head should move each frame
        self.__step = speed * direction

        # the length of a step
        self.__step_length = self.__step.length()

        self.pos_head = Vector2(pos_src)
        self.points = [(self.pos_head.x, self.pos_head.y)]

        self.color = color

    def update(self):
        self.__distance_traveled += self.__step_length
        if self.__distance_traveled < self.__distance:
            self.pos_head += self.__step
            self.points.append((self.pos_head.x, self.pos_head.y))
        else:
            self.destroy()

    def destroy(self):
        missiles_attack.remove(self)

def draw_missiles():
    for missile in missiles_attack:
        pygame.draw.lines(screen, missile.color, False, missile.points, 2)

def update_missiles():
    for missile in missiles_attack:
        missile.update()

So when i want to create a missile, i pass the src and dst position of the missile and then add it to the list of attack missiles, both the draw_missiles and update_missiles functions are called for each frame inside the game loop.
The idea behind the trajectory is to work out a new point in the line defined by the src and dst position each frame, i have three problems with this approach:
problem 1
I don't know how to draw the missile heads, in the video you can see that the heads are like a white pixel, i tried to take the last two points of the missile.points list and draw a new line with those points to represent the head, the problem is that the line length changes when the speed of the missile changes so it not works.
problem 2
Seems silly to store all the points of the trajectory in a list, seems like is too much waste of memory, i can't think in another more efficient solution with the same 'graphical results'.
problem 3
Another thing i tried is instead of use the pygame.draw.lines function use the pygame.draw.line one, the draw_missiles function will be something like this:
def draw_missiles():
    for missile in missiles_attack:
        pygame.draw.line(
          screen,
          missile.color,
          (missile.pos_src.x, missile.pos_src.y),
          (missile.pos_head.x, missile.pos_head.y),
          2
        )

Well, now i don't have to store all the points, which is a good thing i think, the problem is that when the line is draw, the results are different than the 'points approach', seems like the line algorithm that pygame uses under the hood not draws the same pixels for a line going from the point A to the point B, that for a line going from the point A to the point C, where C is a point in the line between A and B.
So how i can deal with this problems, what is the most reasonable approach to implement this kind of behavior?


texts: How can I quickly check if my sprite tiles well?

texts:
I am trying to create tilemap sprites that tile nicely, but checking how well they tile is really cumbersome.

Ideally, I'd like to have an image editor that shows a layout like this, so I could see if it tiles well without a manual check:

     [img]
[img][img][img]
     [img]

What programs can do this, or how can I otherwise make this easier?


texts: What type should you use for keeping game score

texts: Lets say you have a high scoring game like geometry wars, why type would you use for the score and how should you handle overflow?


texts: I am making a small game where I store information about the world around the player (like tiles) using a small 2d array of integers. In the game you can scroll the screen to the left or right. I also want to be able to read portions of the world from a file instead of loading the entire world at once for performance reasons. My concept of doing this is when the camera has scrolled a certain amount, shift the array by a certain amount and replace the old array data with new information from the file. I'm not sure if this makes sense performance wise or if there is a more performance friendly way of doing this so I was wondering if anybody could provide some insight. I drew an image to show what I am talking about.


texts: How do I test for intersection of a ray and part of a capped cone / cone frustum?

texts:
The formulas to calculate the intersection between a ray and a capped cone / cone frustum are already widely known (see http://lousodrome.net/blog/light/2017/01/03/intersection-of-a-ray-and-a-cone/ or How do I test for intersection between a ray and a cone?)
However, I have to test for the intersection between a ray and part of a capped cone.
That means instead of having a surface doing a full revolution, it's just one quarter of it, for example.

The aforementioned formulas can handle a capped cone, but they are not suitable to determine the "revolution intersection angle".
What would be the best way to solve this problem?

My idea is to first take the standard formula to intersect with the full cone and then use the parametric representation of the cone (see https://de.wikipedia.org/wiki/Kegel_(Geometrie)#Analytische_Beschreibung parametric representation is only on the German page), solve a linear equation system and then applying the inverse trigonometric functions to get the t parameter...
I'm also thinking about some inequality tricks or applying the tangent function, but had no luck so far...


texts: What's the best way to write fade in out function?

texts:
I want to create a continuous fade in and out.

I'd like to have some function F(time) that returns values increasing from 0 to 255, then from 255 back down to -255, and repeats, as time progresses.


texts: Best practices for playing sounds in iPhone games

texts: What are the best practices for playing sounds in iPhone games? Specifically, what are the best practices while playing sounds simultaneously without affecting other processing much. Is there any recommendation about how sound files must be made to suit the processing?


texts: What roles are important when staffing up a mobile studio?

texts: For a new studio that will be focusing on social, mobile platform games. What are roles do we need to fill and how many of each role would be ideal?


texts: iPhone point-and-click adventure game port structure

texts:
I am porting an AGS game to iPhone, and was wondering what the best approach to the port would be?

How best would you structure your code and assets?

More specifically, how would you deal with say 100+ scenes. My initial approach is to create a scene superclass with things common between all scenes, like backgrounds, music, doors, windows, characters. Then for each scene an inherited version of that superclass with more particular things like checks, dependencies etc. Upon entering the scene, you'd check for dependencies and go from there. This is all off the top of my head mind you, so probably forgetting quite a bit.


texts:
Situation:

Big open world-ish level
Different types of real estate:

Houses including some land around it
Just houses without land
Flats on different floors

How to express AI ownership of any of those types that I could use in game logic?

My first thought was to use collider around the area as a trigger that I could use to detect if "guest" enters the area and program AI to only react if certain criteria is met (e.g sees the guest, friend vs enemy) but:

Most areas are pretty complex - I would need to use mesh colliders
It would get rather expesive if I had many areas around the player active (urban environment)
I also need the concept of "my area" for other logic - e.g pathfinding, place items etc


texts: Random numbers inside instance (Game Maker)

texts:
I've recently run into a weird problem. When I create instances through with(instance_create){ ... }, I can always randomize their variables individually (inside {...}). However, when I try running

randomize()
random(...)

inside their object (in one of the events), they are all synced. Please tell me this isn't a major Game Maker flaw and, most importantly, how do I fix this. Thank you!


texts: Unity smooth local rotation around one Axis, oriented toward a target

texts:
I want to acheive the same rotation you see in the inspector.
In short: a smooth local Y rotation, toward a target

I have a Vector3 orientation:
Vector3 dirOrientation = targetToLook.position - movingCamera.position;

So, every Update, what should I do ? I try many thing, but I don't realy understand Quaternion...

I just want to rotate localy in Y, toward a precise moving target, NOT in X or Z. and smoothly with some Lerp or Slerp.

Thanks !


texts: Setup VertexPositionTexture array for a texture2D at a location

texts:
I am trying to adjust the following code to render a quad on a 2D texture at a specific location and specific size. Currently this code will render a fullscreen quad, which makes sense since the POSITION semantic is being set to the fullscreen size.

My issue, is that I don't know how to adjust the POSITION semantics in the declaration below to use the specified location and size of a texture.

private short[] indexData = new short[] { 0, 1, 2, 2, 3, 0 };

private VertexPositionTexture[] CreateTriangles(Vector2 location,
                                                float width, float height)
{

    // how do I get these values, and where do I set them below?
    float topleft = ??;
    float topRight = ??;
    float bottomLeft = ??;
    float bottomRight = ??;

    VertexPositionTexture[] vertices = new VertexPositionTexture[]
    {
        new VertexPositionTexture(new Vector3(1f, -1f, 0f),
                                  new Vector2(1, 1)),
        new VertexPositionTexture(new Vector3(-1f, -1f, 0),
                                  new Vector2(0, 1)),
        new VertexPositionTexture(new Vector3(-1f, 1f, 0),
                                  new Vector2(0, 0)),
        new VertexPositionTexture(new Vector3(1f, 1f, 0),
                                  new Vector2(1, 0))
    };

    return vertices;
}

All I'm trying to do is render a quad overtop of a texture at a specific location. If I use the code as-is with my texture is will stretch the texture to the entire size of the screen (again, makes sense because of how the POSITION semantic is being set).


texts: Sources for archer vs other unit comparisons?

texts:
Going around the web and gathering info about units gets you in an avalanche of information that can takes years to sort out.

You can research historic battles but most of them are imbalanced in one way or another and its hard to get usable data.

When people ask me how to accurately compare an archer to a footman i have no idea what to tell em. I've built up an arbitrary comparison over the years and its what I use, but relaying it to others or justifying it to superiors is quite a murky realm.

Anybody know of a source that has simplistic comparisons?

100 shortbow archers are charged by 100 swordsmen without shields or arrow stopping armor.

100 shortbow archers are charged by 100 horsemen without shields or arrow stopping armor.

How many of the melee troops roughly would actually make it to the archer line?

We know that if few reached the line they could break it. And this many times is achieved by surprise or particular tactics or terrain advantages. But what does the data look like when these units started out of range and went at each other at a direct line on a level field.

The basic data is hard to come by. Building on top of is actually way easier as you can scale armor up by tapping many sources that have distilled data on arrow penetration rates for the various armors. Even archer accuracy is easier to come by than this.

Any ideas?


texts: Full Engine or Not: C++ Programmer Trying to get into Game Development

texts: I'm a fairly experienced programmer, and I want to try out doing some game development. However, I am unsure of whether or not to use a full engine like Unity or just start with something like OpenGL. How much flexibility/extensibility do you use going with Unity. I know it can be used with minimal coding, but if you can write your own code, will it constrain you later down the line? For my first project I want to just build a simple tile based rpg and build it up to something larger. Any advice is welcome.


texts:
I'm currently making my own little 2d text based game and I've got a 11 / 11 grid where a monster spawns in the middle and when i stand on it's position and it brings me to another 11/11 grid where i fight the monster. I'm going to make it a turn based theme where it starts on my turn and i can only move a certain amount of spaces and the monster can only move a certain amount of spaces and when are abilities are in range we can use them etc etc etc,

I want it so every time i encounter a monster it sees where i am on the grid and see's if its a low level area or a high level area, if it's a low level area it will spawn a Slime , wolf or pig. or high level area it will spawn a dragon , giant etc. Is there a better way to do it than what i'm currently doing it. Right now I've started to low level area.

What i'd like it to do

if monster = pig,wolf,slime , give it a certain amount of stats and health then start the fight

if monster = giant,dragon , give it a certain amount of stats and health then start the fight

Is the current way i'm doing it good or is there a better way?

  public static void monster_encounter() {
  Random gen = new Random();
  final int monster_gen = gen.nextInt(3);
  if( monster_gen == 0) {
  System.out.println("You're fighting a: Wolf");
  }
  else if( monster_gen == 1) {
  System.out.println("You're fighting a: Slime");
  }
  else if( monster_gen == 2) {
  System.out.println("You're fighting a: Pig");
  }

  }


texts: Unity animation editor's object rotation is doing weird

texts:
When using the Unity timeline to create an animation or by using the animator itself, I am unable to properly rotate an object. Whenever I do rotate it, it will usually go something as follows: From 0 -> 20 = 0, -132, 67, -89 and then 20.

I have tried to manually set the rotation values, doing this does help, but this means that I will have to do everything manually which is a crap ton of work. I also did make an animation yesterday with the timeline animation with no problems at all, in the morning there were the same problems and I have no clue how it suddenly worked.

I have also tried selecting rotation in the animation window and changing Euler to Euler (Quaternion) or Quaternion itself. This doesn't work, it will only have a less spinning outcome.

I would like to know if anyone has any solutions for this problem. I am using Unity version: 2018.3.5f1.

Thanks for any help in advance.


texts: colliding btRigidBody objects behave strangely when moving slowly

texts:
I'm trying to use Bullet Physics in my iOS game. The engine appears to be correctly compiled in that the demos work fine.

In my game I have the player's ship and some enemy ships. They're defined as btRigidBody objects and btCollisionObjects and I'm using btSphereShapes for collision.

At 'fast' speeds, collisions appear to happen sensibly - things collide and nothing goes 'weird'. If the speeds are very slow though and the player's ship touches a non-moving object the collision happens, but then the player's ship moves at incredible speed over the next few frames and appears a long distance from where it collided - completely out of proportion to the speed it was moving before impact.

To move the things around I'm using setLinearVelocity() each frame, ticking the physics engine, then using getMotionState() to update the rendering code I have.

Part of the issue might be I don't quite understand how to set the correct mass or what the best speeds are to use for anything. I'm mostly sticking numbers in and seeing what happens.

Should I be using Bullet in this way, and are there any guidelines for deciding on the mass of objects? (am I right in assuming that in collisions heavier objects will force lighter objects to move more)


texts:
I am working through the popwindow sample code provided in the documentation here. So far my code opens up an instance of PopupExample when user clicks on a sprite. But I am unable to understand how PopupExample's position and size is being determined. The line below from the sample code, is setting the activator rect of PopupExample to buttonRect. And buttonRect is initialized to default values, which should be x=0f; y=0f; width=0f; height=0f.

PopupWindow.Show(buttonRect, popup);

When I run the code and click on the sprite, the popupwindow shows up on the upper-left corner of the IDE(screenshot below). I was expecting it show up somewhere within the scene itself. Why is it not contained within the scene? Also how can a widow with width and height initialized to 0f be visible at all?


texts: Is there an AIR native extension to use GameCenter APIs for turn-based games?

texts:
I'm planning a turn based game using the iOS 5 GameCenter (GameKit) turn-based functions. Ideally I would program the game with AIR (I'm a Flash dev), but so far I can't seem to find any already available native extension that offers that (only basic GameCenter functions), so my questions are: Does anyone know if that already exists? And secondly how complex a task would it be to create an extension that does that? Are there any pitfalls I should be aware of etc.?

** UPDATE **

There does not seem a solution to the above from Adobe. For anyone who is interested check out the Adobe Gaming SDK. It contains a Game Center ANE which I've read contains options for multiplayer but not turn-based multiplayer, at least it's a start. Comes a bit late for me as I've already learned Obj-c!


texts: When animating for the Android platform is it a better practice to create a sprite sheet with multiple states for each sprite on a single picture or should I instead export individual images for each character/state/etc.? Which option gives me a smaller file size for resources and which is easier for the programmer to animate?


texts: differences between opengl 3 and opengl 4

texts: I'm just getting started with game programming and I want to start learning opengl. I found a very great tutorial from scratch to get started with opengl 3 and I'm wondering if there is a big difference between openGL 3 and openGl 4. Or I should ask, does openGL 4 make openGL 3 obsolete, or I can start with openGL 3 and then I can move to openGL 4?


texts: I have a project where I am getting a very weird thing in the build. Normally, the scene is working fine but some of the objects are showing like this. For example, the tracks or some of the trees.


texts: How can I switch between DirectX and OpenGL renderer in my engine?

texts:
I am currently developing my engine with DirectX, but I want to make it cross-platform in the future, using OpenGL.

How can I check which platform my engine is running on?
And can I use an if statement after I've checked the platform to say which renderer to use?

I currently have an abstract renderer and a DirectX9 renderer as it's child.


texts:
So I'm just starting to try to learn unity development with C# using this tutorial but I cant add the script to any game object and I get the following error:

Code of the script:

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    public Light myLight;

    void Update()
    {
        if (Input.GetKey("space"))
        {
            myLight.enabled = true;
        }
        else
        {
            myLight.enabled = false;
        }
    }
}

I know it's been answered before but I've done everything I read, I did my homework and I still cant get around this issue. I allready checked the name of the class and its the same as the file's name.
I think it may be something regarding installation (?) I installed unity hub and it installed Unity and Microsoft Visual Studio by itself.

Unity version: 2019.3.3f1
MS Visual Studio version: 16.4.5
MS Net Framework version: 4.7.03062

I honestly dont know what else to do people! Please help!


texts: Unity loop through list and match PlayerPrefs

texts:
I have a list of stickers and when a player completes a level they get awarded a sticker which I save into PlayerPrefs. I want to be able to return the list of sprites saved into PlayerPrefs on the awards scene.

I have not been to loop and match the PlayerPrefs. I am not sure how to go about this.

public class StickerManager : MonoBehaviour
{
    public List<Sprite> stickers = new List<Sprite>();
    public List<Sprite> unlockedStickers = new List<Sprite>();

    public void UnlockSticker (int id)
    {
        PlayerPrefs.SetInt("sticker", id);
    }

    public List<Sprite> LoadUnlockedSticker ()
    {
        int i = 0;
        foreach (Sprite spri in stickers)
        {
            if (PlayerPrefs.GetInt("sticker", i) == stickers[i])
                unlockedStickers.Add(stickers[i]);

            i++;
        }

        return unlockedStickers;
    }
}


texts: I saw the general level design question but not much of it applies to building good solid levels for RTS games. Where can i find information on rules and mechanics of RTS level design?


texts:
I'm creating a 2d game and I want to make it so that tiles are destructible whenever a projectile collides with a tile, the problem is I don't know how to get the tile that the projectile is colliding with, I would like to make it so that it area of damage.

However for now I want to make it so that once the projectile reaches the ground it destroys the tile it's sitting on I've made a collider2d to help me with that but I still have no idea how to get the tile that's the projectile is sitting on.

IEnumerator OnCollisionEnter2D(Collision2D x)
    {
    Vector2 hit = gameObject.transform.position;
    Debug.Log("y" + hit.y);
    hit.y =- 3; // What y should i put here in order to make sure its the same as the tile the projectile is sitting on
        if (x.gameObject.tag != "Player")
        {
        Collider2D[] collidedwith = Physics2D.OverlapCircleAll(this.gameObject.transform.position, radius);
        tilemap.SetTile(tilemap.WorldToCell(hit), null);
    }

A screenshot for better explanation (I would like to get rid of the blue tile):


texts: How do I get a relative rotation between two positions?

texts:
For example, I have two objects: a & b.

a's position is 12, 16, -2 and b's position is 14, 16, -3

I need to know how to find a relative rotation between them.

By relative rotation I mean this: a's pitch and yaw so a is looking at b.

I have no helping methods like lookingAt() etc. I only know a's x,y,z,yaw,pitch and b's x,y,z.

Any help?


texts: Help streaming resources (maps, sounds, music, etc) from many files for contiguous world

texts: So I'm creating a game and I would like to know how to perform resource streaming (rather than loading the whole file into the buffer) for things such as my maps, sounds, music, etc. I'm using C++ and DirectX9 if in case you need to know.


texts: For Vertex Buffer Steaming, Multiple glBufferSubData VS Orphaning?

texts:
I was learning OpenGL recently.
In games, we need to update the position of game objects frequently, and they will come in & out of screen constantly. So it means in rendering we need to update the vertex buffer quite often as well.

In OpenGL's context, one intuitive way is to use glBufferSubData to update those that changed.

But I also read online a trick called Orphaning that creates a new buffer data and upload the whole vertices data to it.

Also due to state chagnes cost and uploading cost, multiple glBufferSubData may also cost more.

Here is my question,

Which method is better?
Is stalls really matters in this case?
Is state changes and uploading cost really matters in this case?

Thanks!


texts:
So I recently designed an enemy that will follow the player when he comes within a certain distance of the object. However, there are times when the player comes in range, only for the "follower" enemy to seemingly reverse before following, or almost kind of circle the player on the way towards him.

I can't quite put my finger on why this is happening, so I have attached my code. I hope someone can give me some advice on how to improve this:

    public class Follower : MonoBehaviour
{
// spawn position and other info of Follower
private Vector3 pos1 = new Vector3(-7f, 0.5f, -7f);
public float speed = 1.0f;
public int Range;
public GameObject target;
private Vector3 targetTran;
private Vector3 diffVec;
private float diffMag;

void Awake()
{
    transform.position = pos1;
    sourceCollFol = GetComponent<AudioSource>();
}
void Start ()
{
    target = GameObject.FindWithTag("Player");
    targetTran = target.transform.position;
}
void Update ()
{
    pos1 = transform.position;
    targetTran = target.transform.position;
    diffVec = (targetTran - pos1);
    diffMag = diffVec.sqrMagnitude;
    // check for range between Player and Follower Enemy
    if ( diffMag < Range)
    {
        transform.LookAt(targetTran);
        diffVec.Normalize();
        transform.Translate(diffVec.x * speed * Time.deltaTime, 0f, diffVec.z * speed * Time.deltaTime);
    }
}
}


texts: Game Loop delay the right way and game speed

texts:
I am a newbie game developer. I am trying to find a right way to create my game loop.

Consider following example.
Simple Android Game
I have a game with a simple gameplay - bouncing ball.

I want to have a control of the ball speed.
Also I want my game to have the same framerate (framespeed) on all devices.

Where the speed logic should be implemented ? In my case I have simple ball object with a velocity vector. I can change the velocity vector properties in order to make my ball move faster or slower, am I right ?
The Main Loop. I have read a lot of about this part of a game. I found this article http://gameprogrammingpatterns.com/game-loop.html . And decided to use this code example

    double previous = getCurrentTime();
    double lag = 0.0;
    while (true)
    {
    double current = getCurrentTime();
    double elapsed = current - previous;
    previous = current;
    lag += elapsed;

    processInput();

    while (lag >= MS_PER_UPDATE)
    {
    update();
    lag -= MS_PER_UPDATE;
    }
   render();
   }

I have a lot of questions about this example.

I have the similar loop in my game.

 @Override
        public void run() {
            while (mIsRunning) {
                processGameInput();
                updateGameState();
                drawGame();
            }
        }

I cannot understand while update(); is called while waiting for a constant delay ? Why not the render method ?
Maybe I am missing something.

Here is how my update for the ball looks like.

   public void updatePosition() {
        mCenterX += mVector.x;
        mCenterY += mVector.y;
    }

As you could see, each time I increase the position of the ball by the value of the velocity vector.

But as can guess, in case of using the example from the article, the update method will be called for instance 100 times. And the render method only once per 100 update method calls.
So in this case I guess, I the ball will be changing its position lagging.

My goal is to control the speed of the ball, for example from 0.1s - 2s.

How can achieve this ?

Please help to understand this topic. Any help would be highly appreciated.


texts: How would I handle collision to all instances of one object? (C# and monogame)

texts:
What I'm saying is, let's say I have a list. That list contains all the tiles in the game. I use this to update them all, draw them all, etc.

for (var i = 0; i < Tiles.Count; i++)
{
     Tiles[i].Update(gameTime);
}

But how can I handle collision from each side of the tile, each side of the player for all tiles, but instead have each tile have its own individual set of collision codes? Because if I have the player box intersect the tile box, it counts as ALL of the tiles..


texts: C# 2D game collision detection huge problem

texts:
I'm making my first game using C# and Monogame and I have a huge problem with collision detection.

The entire code is in a link below:

My game code

So, I use Vector2 to keep position and dimensions of objects such as characters and blocks which are elements of the map.

The problem is here(I guess):

    protected virtual void CollisionDetection()
    {
        if (!CanGoRight()) pos.X -= velocity;
    }

    protected bool IsTouchingLeft(Basic2d asset)
    {
        return pos.X + dims.X / 2 > asset.pos.X &&
               pos.X - dims.X / 2 < asset.pos.X &&
               pos.Y + dims.Y / 2 < asset.pos.Y - asset.dims.Y;
               //pos.Y - dims.Y / 2 > asset.pos.Y;
    }

    protected bool CanGoRight()
    {
        foreach (Basic2d asset in Globals.GameAssets)
            if (IsTouchingLeft(asset)) return false;
        return true;
    }

The Hero object stops while walking on the floor when the Basic2d objects ends. But I have in my code that he's supposed to stop if his bottom side(bottom of the feet)(in pixels) is lower than floor's object upper side. And he seems not to see the brick(Basic2d object) that is a real obstacle on his way, he just goes through it.

I have no idea what is wrong.


texts: What are some ways of sorting through zero-experience programming candidates?

texts:
I work for a relatively small company.  We don't get a lot of resumes from people with experience, yet we're in a position where we should hire people to grow.  We pretty frequently get resumes from people just out of school.

We'd like to try to find the diamonds in the rough, but flying non-local people out and taking a day out of several people's week to do a sit-down, in person interview is expensive.  We also do phone interviews for any semi-promising candidates, but those can take a while to set up, and are usually a couple of man hours lost.

We've considered implementing a programmer test, but we have yet to figure out a good one that other studios aren't using.

What are some practices that your studios use to look through these people, with minimal internal overhead?


texts: How do I change a LÖVE2D game executable's icon?

texts:
I merged my game.love file and the love.exe with the command copy /b love.exe+app.love game.exe. But the resulting executable has the default LÖVE2D icon.

Is there a way to change that icon to another one?


texts: Help deciding data structure for spatial partitioning, using only value-types in c#

texts:
I simply want to implement some sort of grid where I can sort units in an RTS into cells, and then for each unit check to avoid other units and attack other units, in 2d.

My map grid is currently 10 000 x 10 000 cells, with 20+ thousand units. To be specific, my grid is sparse but the units move together in very dense groups of about 300 each (like an ancient army type of formation). So cells will either be extremely dense, or completely empty, no in-between really.

My issue in deciding is that I am using Unity job's system and burst compiler. If you do not know, jobs is a multithreading system, and burst is an LLVM based compiler outputting very fast assembly. The limitations of these systems is you can only use value types. So no classes.

I have looked at using a MultiHashmap, but from what I read this can be very slow because I need to run a hash function for every unit. Then when I want to iterate al units in a cell, this is much slower than iterating an array. Especially, because I will also be checking the 8 neighbour cells for each unit as well. That's a lot of hashing being done. Finally, I have to clear the map every frame. The advantage here is Unity provides a container NativeMultiHashMap which is thread-safe, so I can build and query it in parallel.

I have looked into quad-trees. But quad-tree does not seem suited to multithreading, especially without using references. So if I did this, it would most likely be single threaded.

My question is, are my above statements correct in thought? Is there a faster way to organize my data? If I go with a hashmap, how can I query it most efficiently?


texts: Unity console error with only a timestamp

texts:
I am getting console errors that only have a timestamp. I am running Unity 2019.1.9f1 on Ubuntu 19.04. I have installed dotnet core 2.2.5 on my machine.

Here is the full error log: https://pastebin.com/7vfAK9fZ

Here is a particularly suspect part of the log:

-----CompilerOutput:-stdout--exitcode: 134--compilationhadfailure: True--outfile: Temp/Unity.TextMeshPro.dll
-----CompilerOutput:-stderr----------
No usable version of the libssl was found
/home/username/Unity/Hub/Editor/2019.1.9f1/Editor/Data/Tools/RoslynScripts/unity_csc.sh: line 64:  3902 Aborted
"/home/username/Unity/Hub/Editor/2019.1.9f1/Editor/Data/Tools/RoslynScripts/../../Tools/Roslyn/csc" /shared /noconfig @Temp/UnityTempFile-2773a2345220fccdfb0171165a73fa25
-----EndCompilerOutput---------------
- Finished compile Library/ScriptAssemblies/Unity.TextMeshPro.dll

How do I fix it?


texts: How can I recreate the Darwin Project's Particle?

texts:
I want to recreate electronic particle in Darwin Project.but I don't know how can I use vfx graph to make this effect.I upload this effect in youtube you can see in the link below:
Darwin Project Electronic Particle Effect Youtube
Condensation


texts: UnityWebRequest won't work unless a breakpoint is triggered before hand

texts:
public void GetLeaderBoard() //Load all game data
{   UnityWebRequest myWr = UnityWebRequest.Get(Url(false));
    myWr.SendWebRequest();
    var text = myWr.downloadHandler.text;
    MonoBehaviour.print(text);
    return;
}

text is populated by an empty string unless I stop at a break point before I encounter it.  The MVC application that's giving me the data is being debugged on a separate solution, also it's going through something called IIS Express, which like runs it or something.  My best guess is that something on my other application doesn't have enough time to send the data unless I stop execution with a breakpoint; however, this doesn't make any sense as myWr.downloadHandler.text is actually being populated with the data (according to the watch I have on, when it stops at the breakpoint on the return), so my other app should be out of the picture at this point.

Edit: So I got it working apparently the whole function needed to be part of a coroutine like so:

public IEnumerator GetLeaderBoard() //Load all game data
{
    using (UnityWebRequest myWr = UnityWebRequest.Get(Url(false)))
    {   yield return myWr.SendWebRequest();
        if (myWr.isNetworkError) MonoBehaviour.print("Recieved error: " + myWr.error);
        else
        {   var text = myWr.downloadHandler.text;
            MonoBehaviour.print(text);
        }
    }

I'll leave the question open if anybody has any explanation for the values I was getting in my watch though (if the downloadHandler was getting data shouldn't it have populated my text field?).


texts: Which is a better way for moving 3d objects in OpenGL?

texts:
I'm learning OpenGL, and I'm a bit confused. I've just learned about projection and modelview matrices which can be used for moving things. This is the first way, which is convenient if I want to move everything. The other way is to calculate the new coordinates, and rebuffer the data. The second one seems a bit inefficient, because I have to rebuffer every single moved objects 60 times per frame. This has an advantage: I know the exact coordinates, and I  can check collision, and other stuffs. If I move my character with manipulating the matrix, how do I know if I hit the wall or not? Should I make the same calculation as the shader, and get the 'real' position?

Which is more practical and efficient solution?


texts:
So this is probably a simple question:

But how come sometimes I see it like this:

GLuint vbuffer;
glGenBuffers(1, &vbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vbuffer);

but when done in multiples:

GLuint VBOs[2]
glGenBuffers(2, VBOs);
glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);

Im curious why glGenBuffers has a & in the first one, and not in the second case. Is it because arrays are always passed by reference? and is vbuffer a POINTER to something or just a simple data structure (GLint in this case).


texts: Create a tornado like particle movement, based on velocity

texts:
For context i'm using Java and Minecraft Forge, however the concept should be fairly standard. To spawn particles you use this function...

world.spawnParticle("largesmoke", posX, posY, posZ, velocityX,  velocityY, velocityZ);

This works fine, however I am trying to give the particle a velocity which will rotate it around a point (the player) and give the effect of a tornado (obviously more will have to be spawned, I also have the random position setup to each particle).

In short, I would like to find a way to give it a tornado like velocity.

Thanks


texts: Shader Graph, add color outline to 2D Sprite

texts:
I'm having trouble creating a shader in Unity Shader Graph (2D) that fills the image from the bottom to the top and adds a color outline along the visible part of the sprite.

I can fill the image and that seems to be working. I can't however add the color outline. I figured it has something to do with using the inverse alpha of an image, but since i'm pretty new to shaders in general I find it hard to implement it.

This is what i currently have:

As you can see I have the substract node there for the inverse alpha. I'm pretty stuck as to where to go next. I cannot seeme to find a relevant tutorial online. I tried implementing a Fresnel effect, but that seems to only apply to 3D images (i had tried to replace the Master with a PBR master and attaching the fresnel, but it had no effect).

What would be the correct approach from here to add the color outline to the sprite, taking in account the vertical fill?


texts: Can I use MobiForms for my game development?

texts:
Just now I found MobiForms. I am planning to create a game for the iPhone using it.

My problem is I know only Objective-C and I have designed only one app (which is also a game) that's currently in the AppStore.

Can I use MobiForms for game development?


texts: What constraint (if any) limits crowd animation variety?

texts:
I have recently noticed something in a large number of sports games relating to the animation of the crowd.

Scenario

Player holes the golf ball and the crowd all clap their hands.  Whilst the faces and attire of the crowd members are different the animation is exactly the same.  That is, the arm and hand movement of each member is identical.

Similar scenarios exist in other sports games; in football games the crowd often stand up and sit down together as well as doing things like "fist pump", wave, etc. in a perfectly synchronised manner.

Question

Why is there no (or very little) variation in the crowd animation?  Is this a memory constraint?  If so, what is the general architecure/design of this functionality and why is it so constrained?  Is it along the lines of "It is more efficient to animate a collection of objects than multiple individuals"?

Or do game developers simply not see crowd variation as an important enough requirement?

As technology and game "realism" advances so quickly, this is something that still strikes me as "wooden" and unrealistic.


texts: How do I avoid going through objects at high speed?

texts:
I am quite the beginner in XNA. I have only recently started using GameComponents. I have a multiplayer game called Better Pong. I move the ball (which is an object) by incrementing the Vector2 (the position) of the ball by the velocity Vector2 and updating the hitbox Rectangle.

However, by having very large speeds (such as (12,12)) the ball might go through the paddle since it just skips through the Paddle's Rectangle "hitbox".

Is there a way to make the ball make smaller movements, so it doesn't go through the paddle (but still move fast)?


texts: How can I include vertex color information in .OBJ files?

texts: The .obj files I export are missing data for vertex colors. Is there a way to include color information in the .obj file? If not, what are the alternatives?


texts: How can I reduce the amount of GLSL code written?

texts:
I am writing a game engine for Linux. It has a sufficiently large number of effects that can be turned on / off. Effects are defined before compiling with #ifdef. But the problem is that I literally have to “wrap” each variable in #ifdef. Another problem is that when adding new effects, I have to rewrite the conditions, since one variable can refer to several effects at once. For example:

#if defined ALGINE_LIGHTING_MODE_ENABLED || defined ALGINE_SHADOW_MAPPING_MODE_ENABLED
uniform vec3 viewPos;                       // Camera position
#endif

#ifdef ALGINE_DOF_MODE_ENABLED
uniform float focalDepth;
uniform float focalRange;
#endif

How could I reduce the amount of re-write needed when adding new effects?


texts:
Assuming I have a simple client-server game, where the server picks random players on a very frequent base, I was wondering what is the best way to select a random player (According to the following constraints):

Solution must be high performance and highly scalable
Random spread should be relatively even (meaning if I have 3 players and pick 99 times, they will all be picked 33 times more or less)
Should only pick players who were active in the past X days (optional, but a big bonus)

The actual DB or data model used to store players isn't an issue here, as we'll select the technology in accordance to our needs.

However, high performance and scalability is (at the moment we have over 60,000 unique daily active players, and we plan on growing even more).

Thanks!


texts:
I'm making an RPG and want to make npc ai to navigate the city. I am using polylines for collision detection, and my map is 2D, but oblique styled. I am considering using the A* algorithm to help them navigate.

I've gotten the A* algorithm to work with a top-down 2D array of nodes:

But am not sure how to go about implementing this in my game.

The overall world is 100x100 64x64px tiles, but the viewport (red box) only shows a small portion of them:

My questions are as follows:

Do I make a 2D 100x100 array, each cell size 64x64 px to mimic the real map?
How do I account for the polyline barriers/collision if 1's (unwalkable) and 0's (walkable) can only be assigned to a square cell?
Performance: is it better to just created a pathing grid for the viewport, or always generate one for the entire 100x100 map?
Barriers/Collision: I create my collision barriers directly in Tiled. Is there a way to programmatically insert unwalkable into the matrix for a given location of the barrier?

I am lost as to where to go next in translating this to my game.

Thanks!


texts: Polygon/Shape definition changes in Box2D 2.1

texts:
I was going through a pretty good tutorial on Box2D here, but I ran into a problem when he made a b2PolygonDef, because the tutorials were made in 2.0, and I'm using 2.1. I could download 2.0 I guess, but I'd really like to know how to update how to do this to the newest version.

If you guys don't want to watch the whole video, basically, he does this in this one:

        private function createWallsAndFloor():void
    {
        // Create the shape (polygon) definition
        var bigLongShapeDef:b2PolygonDef = new b2Polygondef();
        bigLongShapeDef.vertexCount = 4;
        b2Vec2(bigLongShapeDef.vertices[0]).Set(0 / RATIO, 0 / RATIO);
        b2Vec2(bigLongShapeDef.vertices[1]).Set(550 / RATIO, 0 / RATIO);
        b2Vec2(bigLongShapeDef.vertices[2]).Set(550 / RATIO, 10 / RATIO);
        b2Vec2(bigLongShapeDef.vertices[3]).Set(0 / RATIO, 10 / RATIO);
        bigLongShapeDef.friction = 0.5;
        bigLongShapeDef.restitution = 0.3;
        bigLongShapeDef.density = 0.0;

        // Create the body definition
        // Create the body
        // Create the shape
    }

I can see that they removed b2PolygonDef and b2ShapeDef because I'm using Flash Develop, so what basically do I do?

(If you don't mind watching videos, he explains what he's doing in the one before this one.)


texts: Manual orbit motion jerks at a certain point

texts:
So I've been trying to make a simple sphere-orbiting-another-sphere test. The smaller sphere is supposed to circle the bigger one based on the mouse location.

Here is my code:

    //script is assigned to the smaller sphere
    screenpos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

    if (screenpos.x <= centerball.x + 2f && screenpos.x >= centerball.x - 2f) //orbit radius is 2
    {
        xpos = screenpos.x;
        ypos = (Mathf.Sqrt(4f-Mathf.Pow((xpos - centerball.x),2)))+centerball.y;
        //generated value of y from an equation
        //equation of circle -> y = sqrt[(r^2)-(x-h)^2]+k

        if(screenpos.y <= centerball.y)
        {
            ypos = -(Mathf.Sqrt(4f-Mathf.Pow((xpos - centerball.x),2)))+ centerball.y;
            //equation of circle when square root has negative sign
        }

    transform.position = new Vector3(xpos ,ypos,0);

The code is quite straightforward. Basic math equations and all. And it works all fine except for when xpos gets close to the values of "centerball.x  ± 2f ".

It stops moving as I approach the value and then jerks forward, skipping an entire set of values of ypos in between.

So I checked my formula and it is absolutely correct. There is no value of xpos where ypos cannot be obtained (no negative squares).

I did a little thinking and came to the possible conclusion that the value of screenpos was rounded off too much (debug.log showed only 1 decimal place), causing the value of ypos to lose accuracy and jump as the value of xpos approached the previously mentioned bounds. If this is the cause, is there a way to record screenposition more accurately or any other way to get around this problem?

And if this is NOT the cause, can someone please explain what is going on here?


texts:
So after working on my game engine for 2 years, I've decided to step into the networking environment. I just don't know if it's a good idea to rewrite the engine, or how much work it will take (but still want to try it). I'm little bit confused by some approaches, so that's why I'm here.

In short I have an architecture like this:
There is a main object, that controls the whole engine world (physics steps, rendering, audio, input, entities). Then there is a Game instance that is running inside the loop and "creating the content of the game".

I already started with ENet, created a small console chatting app - but packets were just strings.  But I'm not sure if I understand the concept of game networking, so here is my idea:

There is a server and clients. Server is controlling everything. Client sends messages.

So basically:
When client connects to the server, server creates new entity. Now, for example, when client presses A, packet is sent to a server containing this information. Server will process it, moves the entity.

Am I right?

So basically, clients does not have anything, except input controller and keyboard. So when they press keys, action is done. And rendering for the scene render, but all they receive is just a "image" of the scene from the server? Or is there something I miss?

Thanks in advance.

Edit1
And also wondering, everything, like physics manager, or whole scene with entities, are present only on the server machine?


texts:
I am creating a game in which I would like the player to be able to click a location and have the character travel to it. This is the code I am trying to use for this:

if (Mouse.GetState().LeftButton == ButtonState.Pressed && prevMouse == ButtonState.Released)
{
    travelTo = new Point(Mouse.GetState().X, Mouse.GetState().Y);
}
if (travelTo.X >= 0 && travelTo.Y >= 0)
{
    if (Bounds.Y < travelTo.Y)        {
        if (Bounds.X < travelTo.X)
            destRadians = MathHelper.ToRadians((float)Math.Atan((Bounds.Y - travelTo.Y) / (Bounds.X - travelTo.X)));
        else if (Bounds.X > travelTo.X)
            destRadians = 90 + MathHelper.ToRadians((float)Math.Atan((Bounds.X - travelTo.X) / (Bounds.Y - travelTo.Y)));
        else if (Bounds.X == travelTo.X)
            destRadians = MathHelper.ToRadians(90);
    }
    else if (Bounds.Y < travelTo.Y)
    {
        if (Bounds.X < travelTo.X)
            destRadians = MathHelper.ToRadians(-1 * (float)(Math.Atan((Bounds.Y - travelTo.Y) / (Bounds.X - travelTo.X))));
        else if (Bounds.X > travelTo.X)
            destRadians = 180 - MathHelper.ToRadians((float)(Math.Atan((Bounds.Y - travelTo.Y) / (Bounds.X - travelTo.X))));
        else if (Bounds.X == travelTo.Y)
            destRadians = MathHelper.ToRadians(-90);
    }
    else if (Bounds.Y == travelTo.Y)
    {
        if (Bounds.X < travelTo.X)
            destRadians = MathHelper.ToRadians(0);
        else if (Bounds.X > travelTo.X)
            destRadians = MathHelper.ToRadians(180);
        else if (Bounds.X == travelTo.X)
            travelTo = new Point(-1, -1);
    }

    //turn the sprite
    if (radians < destRadians)
    {
        radians += .06f;
    }
    else if (radians > destRadians)
    {
        radians -= .06f;
    }

    //move sprite
    Bounds.Offset((int)(2.5f * (float)(Math.Cos(radians))), (int)(2.5f * (float)(Math.Sin(radians))));

    //remove the destination if the player is close enough
    if (Bounds.Intersects(new Rectangle(travelTo.X, travelTo.Y, 1, 1)))
        travelTo = new Point(-1, -1);
}

What I want to happen is for the sprite to do two things each game loop: Turn toward the destination a little if it is not already pointed there, and move forward a little.

Right now what happens is this:

When the destination is above the sprite, it continually moves straight across the screen to the right (0 radians).

When the destination is below and to the left of the sprite, it turns around in a continuous circle.

When the destination is below and to the right, the sprite travels straight accross to the right until it is directly above the destination, then turns and proceeds down in a series of semicircles until it reaches the destination point.


texts: Unity 5: Accessing a C# variable from Javascript

texts:
I've set up a SQLite database with Unity. Into this I would like to add the current CPU Utilisation. The SQLite scripts are in Javascript and the method for finding the CPU utilisation is in a C# script, I have tried changing the javascript to C# but I am not that skilled. Ive tried several methods, each giving me errors:

(http://www.41post.com/1935/programming/unity3d-js-cs-or-cs-js-access)

private var csScript : ClientValues;

function Awake()
{
csScript = this.GetComponent("ClientValues");
}

using this method gives me the error "The name 'ClientValues' does not denote a valid type ('not found')"

and if I use (http://answers.unity3d.com/questions/272122/can-i-pass-a-value-from-a-c-script-into-a-java-scr.html)

var curValue : int;
var gObject2 : GameObject;

function Update()
{
var cSharpScript = gObject2.GetComponent("Clientvalues");
curValue = cSharpScript.myValue;
}

I get the error: 'myValue' is not a member of 'UnityEngine.Component'

Is this something to do with me using Unity 5?
What can I do to have the Javascript access the C# value?


texts: How to put the game object to the upper left corner of the screen in Unity and make it visible entirely on all screens of mobile devices

texts:
I have game object which displays health indicator in my 2d video game in Unity. This gameobject contains a lot of sprites and i put it into left/top corner of the screen. In my game editor it is visible entirely but on my mobile device is visible only half of it. How can i make it visible entirely on all screens? Can anyone help me to solve this problem please.

P.S.
I have some ideas how to do this:
1. Create health indicator from GUITexture elements. But it is not good for me, because health indicator consists of a lot of small elements and it will take a lot of time for me to resize every GUITexture according to my needs.

Put my gameobject with health indicator into another gameobject with zero transform, and then put parent GO into top/left screen using Camera.main.WorldToViewport method.

But may be there is more easy way to do this?


texts: Why create meshes instead of using Planes?

texts: I'm working on a top down 2D game in Unity and I want to create levels dynamically. All tutorials I find tend to talk about generating meshes so I've followed some great tutorials such as this one. However, here's where I'm not understanding the point. What's the difference between doing all that work to render a plane when you can just use the Plane object with the height/width configured to match what the manual creation has?


texts: Is there any reasons to make sprites and bodies line up?

texts: So in LibGDX the Sprite objects position is where it's 0,0 mark is in the word.  In Box2D a a bodies position is in it's center.  So to line these up when you update the sprites position with the bodies position you would adjust it by half the width and height. But it seems to me theres no reason to worry about that. Because the relative position is always going to be the same, and that it'll just waste calculations lining it up. Is there any reason I should do it?


texts: Better to use fixed sprite size or variable sprite sizes in a sprite sheet?

texts:
you have N frames for an animation (an idle animation for example) of a 2D character. What is the best resolution to use for each frame? The problem is that if you save the N frames such that each of them has the size of the minimal bounding box enclosing the character, when using a call like:

// draw frame i at (0,0)
sprite.frame(i).draw(0, 0)

your character movement will be wrong, that is, it will move back and forth.
The other option is to set the width and height of every frame to the maximum width and height calculated using every frame.

What is, in your experience, the best practice to follow?


texts: I made a potion that displayed and rendered perfectly in 3DS max. When I imported it to Unity it didn’t render correctly as the transparency was all over the place. I first imported it with a png texture with a separate png map for the alphas. I then tried using a .tga and a .psd file with alpha channels set up within the file but I got the same issues happen with both file formats. Does anyone know how to fix this I cannot seem to work it out.


texts:
I am working on a game that contain 1000+ buttons starts from 0 - 999 with 3 decimals like 0-9, 00-99 and 000-999. if the user click the button the button image want to change. it working fine for me but the button with the name and Number(button name and button text both are same)50,100,200,300,400,...900 are not updating the ui. it showing an error like the object is destroyed but you are still trying to access it. but the button and the components in the buttons are not destroyed. i checked my code too.

        if (GameObject.Find (seatNo).GetComponent<UISetup> ()) {
            print ("Available");
        } else {
            print ("Not Available");
        }

here i tried to find the script is available or not. only for the buttons i mentioned above it's telling "Not Available". All others are working fine. but in the same time while running the game the script is available in the gameobject

I am calling the method from another script like this

        UISetup button = GameObject.Find (seatNo).GetComponent<UISetup> ();
        button.changeBtnBG ();
        button.valueUpdates (chip);

in UISetup.cs i use this code to change the Image Source

public Sprite RedSelectedImg;
public Sprite GreenSelectedImg;

public void changeBtnBG(){
    print ("<-------------select img changed-------------->");
    if (redBtn == false) {
        this.GetComponent<Image>().sprite = GreenSelectedImg;
    } else {
        this.GetComponent<Image>().sprite = RedSelectedImg;
    }
}

I am using unity 5.6.0.
i don't know what's the error. Anybody please help. Thanks in Advance


texts: Do realtime reflection probes and precomputed GI work on iOS in Unity 5?

texts:
Seems they don't from my tests but just to double check.
My setup is made up of a few objects marked as static, all sharing a standard shader material with some emissive color,  GI set only to precompute and a realtime reflection probe (set to render on every frame) attached to the player, which is the object that moves and passes near the emissive objects. The player has a metallic material, also standard shader-based.

In the editor, this generates reflections on the player as it passes near an emissive object, as you'd expect.

On iOS, the player looks dull, very dark, and no reflections appear on its surface.

I also tried setting instead the probe to Custom and tell it to render from within a script, since I can't just pre-bake the probes, because the static objects are brought in at runtime. This doesn't seem to work either: the probe doesn't seem to render anything.

Any ideas?


texts:
Yesterday I played around with Unity 4.6 and I came up with a question about animation.

I have an fps-survival project (most for educational purpose).

I use the default build-in fps camera controller that comes with unity asset and adding a script for head-mob.

Now I animate a "falling" animation. The animation is in the  First Person Controller object. Although I have two "arms" as children in my FPS controller, I want in each frame of my animation to move the arms but when I click in the each arm , the animation window don't show me the correct state of the animation, and I need to get back to where I attach my animation to show again. I don't know what to do. I can't animate the hands in seperate file cause I don't see the falling frame from the FPS controller.(which is more a visual than a technical problem)I want to point out that I need to use both my hand objects and I am preety novice so if you could tell me in steps what to do.

I attach some images bellow to see how my enviroment is setted up.

When I select the FPS controller

After I select each hand


texts: Affine transformation: rotate a plane parallel to another plane

texts:
I am writing a function that extrudes a 2D shape along a 3D spline, as found in 3D modeling software.

I need a way of translating a set of points P so that they all lie in a new plane L (preserving distances between points).

P is all points where Z = 0;
L is defined by (0,0,0), with the normal vector N.

I am using Processing, it has common matrix and vector functionality (but no quaternions)
A conceptual or pseudo-code answer is OK.