texts: Retrieving components from game objects (entities)

texts:
Using C# and XNA 4, I've made the decision to go for an entity-component based design for my game after reading such posts as this and this, but I'm now struggling to find how to retrieve components once they've been added to an entity.

Some articles I've read say that when a component is created, register it with the system that will act upon it, using a messaging system. A drawback I see here is that if a system needs 2 components to act (say CollideComponent and PositionComponent) then this gets complicated (and I can't figure how it would work).

The other possibility, and the one that I'm currently pursuing, is to have a system ask whether an entity has a particular component when it needs it. However I've not seen any code examples, only theory on the net, so I've been trying to muddle it together. Some code here might explain how far I've got :

First a System:

public class RenderingSystem : IGameSystem
{
  public void PerformAction(IQueryable<IGameObject> gameObjects)
  {
    foreach (var gameObject in gameObjects)
    {
      RenderableGameComponent renderableGameComponent = gameObject.GetComponent<RenderableGameComponent>(ComponentType.Renderable);
      if (renderableGameComponent != null)
      {
        this.spriteBatch.Draw(renderableGameComponent.Texture, renderableGameComponent.DrawablePosition, Color.White);
      }
    }
  }
}

Now the actual GameObject:

public class GameObject : IGameObject
{
    private List<IGameComponent> gameComponents;
    private ComponentType componentTypes;

    public void AddComponent(IGameComponent component)
    {
        this.gameComponents.Add(component);
        this.componentTypes = this.componentTypes | component.ComponentType;
    }

    public T GetComponent<T>(ComponentType componentType)
    {
        return (T)this.gameComponents.FirstOrDefault(gc => gc.ComponentType == componentType);
    }
}

And finally the Component and ComponentType enumeration :

public class RenderableGameComponent : IGameComponent
{
    public Texture2D Texture { get; set; }

    public Vector2 DrawablePosition { get; set; }

    public ComponentType ComponentType
    {
        get { return ComponentType.Renderable; }
    }
}

[Flags]
public enum ComponentType
{
    Renderable = 1,
    Updateable = 2,
    Position = 4,
}

Now as you might be able to see, I'm trying to use bitwise operations on the ComponentType enumeration that every Component of each GameObject has. The reason being I thought this would be a much cleaner approach when trying to get the required Component out of the GameObject when asked by a System (also refer to link 1 above).

I'm trying to get away from passing in a type, and doing an iteration over all the Components of a GameObject. eg:

foreach (var component in this.GameComponents)
{
  if (component.GetType() == requestedType) { return component; }
}

This is because when there are a few hundred bullets on the screen and a CollidableSystem is created, it will massively slow the game down checking every type. I've had experience with this when creating a previous game, but admittedly, that was using an inheritance based design system.

It worries me that for each System that is created, it will have to iterate over every GameObject every tick asking the same question every time, "Do you have the component I am looking for ?" and still doing a lot of casting and null checks.

Now my question is this. I want to know whether there is a de facto design pattern for getting Components from GameObjects that don't require null checks or casting ? Someway a System will say "Give me this component, I know that you have it" and not bother wasting time asking those GameObjects that don't have the Component. Tell, don't ask.


texts: How to combine multiple sprite sheets from multiple sources (Actionscript/Starling)

texts:
In starling, it's faster if you use BitmapText instead of traditional text. Which is well great except for one issue. Right now the sprite sheet I was making was with a single Fla. I just created the sheet from Flash IDE.

The bitmap text however is generated using a tool like BMFont . Which generates it's own sprite sheet. Now, imagine I have three or four types of texts . Also for some reason I have multiple Sprite sheets of assets.

So the question is, how do I stick multiple sprite sheets together. Is there any available tool for it?

Does using multiple sprite cause performance issues?


texts:
I have a array of six float4x4's in my shader.
cbuffer pseudeocb
{
    float4x4 Mypseudo[6];
};

I need to set these in my code.
ID3DX11EffectMatrixVariable* Pseudo;
void SetPseudo(CXMMATRIX M) { Pseudo->SetMatrix(reinterpret_cast<const float*>(&M)); }
Pseudeo = mFX->GetVariableByName("Mypseudo")->AsMatrix();

This will set one. How do I set six of them? Do I need a SetPseudo function?
Can I do something like the following:
XMMATRIX *p = new XMMATRIX[6];

or

XMMATRIX p[6];


texts: How to address a function inside an if condition using C# in unity 3D

texts:
I am new to game development and have very limited idea of C# syntax. I was watching unity 3D tutorials of UI and thought of using ModalPanel.cs and TestModalWindow.cs
In a quiz game where 3 choices are there of a question and total 5 questions are there

Now suppose in

public void TestNYCI ()
{
   modalPanel.Choice(
         " string? ",
         icon,
         TestYesFunction,
         TestNoFunction,
         TestCancelFunction);

   // Here I want to use an if loop
   // if ( condition)
   // where condition means choosing of a function among
   // TestYesFunction, TestNoFunction, TestCancelFunction

   //Statements

   // If suppose TestYesFunction is true I want
   // to increment the count and write it as score
}

And will repeat the process in rest of the 5 functions.

Can someone please provide a suitable syntax to address the problem.


texts: using per pixel collision for an elastic response

texts:
I realize this might be open ended ended but curious if I just did some over kill...

I had this

http://xbox.create.msdn.com/en-US/education/catalog/tutorial/collision_2d_perpixel

and i reworked it to work with my animation code in XNA and what not.  It works well, but now I want to use this to decide if there was a collision and to have the items (characters) bounce off eachother elastically.  Was the per pixel too much and I could of just used a bounding box ? (in fact would that of been preferred for what needs to be calculated in the response for an elastic collision?)

Looking for guidance really.


texts: Wrong intersection: Bounding Sphere and Ray

texts:
I've got a huge problem with BoundingSpheres and Rays in XNA and I really don't know how to solve it.

The problem:

foreach (BoundingSphere s1 in GetCollisionHullBoundingSpheres())
   if (ray.Intersects(s1) != null)
   {
      System.Console.WriteLine("Sphere: " + s1.Center + " Radius: " + s1.Radius);
      System.Console.WriteLine("Ray: " + ray.Position + " Direction: " + ray.Direction);
      System.Console.WriteLine("Ray: " + ray.Intersects(s1).Value + "\n");
      return true;
   }

The collision hull bounding spheres are the spheres from the mesh and
the ray is calculated by using the playerposition and the vector (0,-5,0) as the direction.

Here is the output:

Sphere: {X:-16,52211 Y:-3,34731 Z:-15,66445} Radius: 5,077909
Ray: {X:75,29767 Y:29,15445 Z:-45,73476} Direction: {X:0 Y:-5 Z:0}
Ray: 35,84612

I can't understand how that ray can intersect with the sphere.


texts: I'm making a WebGL game in a 90s DOS games style. I'm trying to use a shader which would quantize colors to get reduced colors look. I found this solution: Palette reduction to pre-defined palette, however I only get 4 colors when I apply the shader (as in the picture). Any help would be greatly appreciated.


texts: I am a 19 year old who has always been interested in video & computer games. I developed the interested for game programming about three months ago and started researching on the profession. The only degrees always suggested on the internet and in books are those of computer science, physics, mathematics, & game development. BSc Information Technology has been my major for the past two years; and even though my university teaches we the I.T. students computer programming (in c++, c#, java) and offers us the opportunity to undertake some computer science courses of our choice in addition to the regular I.T. courses, I am feeling insecure about my prospects in getting into the profession. My question is: Will a game development company hire me if I exhibit good math, physics and game programming skills with an I.T. degree? If NO, will I have to obtain an MSc in a much more related course.


texts:
I have a fairly straight forward 2D game written in XNA. I'm finding that it arbitrarily drops from 60fps to 40fps.

I've tested this drop extensively and have concluded it's not related to graphics or the hardware being taxed. What's even stranger is that if I put the window in and out of focus a few times the fps jumps back up to 60.

Sometimes the game load sup at 60fps then I put the window out of focus and back in and it drops to 40fps. This happens anytime, including in the main menu where nothing besides two sprites are being drawn, I've even removed rendering of all sprites just to be sure and it STILL happens, so just a black screen with nothing besides a graphics device clearing the screen.

And before anyone asks, yes, I've manually polled my own functions and have found that everything is being updated and drawn very quickly, it just seems that XNA is taking its sweet time to actually call the update/draw functions.

Does this sound familiar to anyone?


texts: Bullet Physics implementing custom MotionState class

texts:
I'm trying to make my engine's camera a kinematic rigid body that can collide into other rigid bodies.  I've overridden the btMotionState class and implemented setKinematicPos which updates the motion state's tranform.  I use the overridden class when creating my kinematic body, but the collision detection fails.  I'm doing this for fun trying to add collision detection and physics to Sean O' Neil's Procedural Universe

I referred to the bullet wiki on MotionStates for my CPhysicsMotionState class.

If it helps I can add the code for the Planetary rigid bodies, but I didn't want to clutter the post.

Here is my motion state class:

class CPhysicsMotionState: public btMotionState {
protected:
    // This is the transform with position and rotation of the camera
    CSRTTransform* m_srtTransform;
    btTransform m_btPos1;
public:
    CPhysicsMotionState(const btTransform &initialpos, CSRTTransform* srtTransform) {
        m_srtTransform = srtTransform;
        m_btPos1 = initialpos;
    }

    virtual ~CPhysicsMotionState() {
        // TODO Auto-generated destructor stub
    }

    virtual void getWorldTransform(btTransform &worldTrans) const {
        worldTrans = m_btPos1;
    }

    void setKinematicPos(btQuaternion &rot, btVector3 &pos)
    {
        m_btPos1.setRotation(rot);
        m_btPos1.setOrigin(pos);
    }

    virtual void setWorldTransform(const btTransform &worldTrans) {
        btQuaternion rot = worldTrans.getRotation();
        btVector3 pos = worldTrans.getOrigin();

        m_srtTransform->m_qRotate = CQuaternion(rot.x(), rot.y(), rot.z(), rot.w());
        m_srtTransform->SetPosition(CVector(pos.x(), pos.y(), pos.z()));
        m_btPos1 = worldTrans;
    }
};

I add a rigid body for the camera:

// Create rigid body for camera
btCollisionShape* cameraShape = new btSphereShape(btScalar(5.0f));
btTransform startTransform;
startTransform.setIdentity(); // forgot to add this line
CVector vCamera = m_srtCamera.GetPosition();
startTransform.setOrigin(btVector3(vCamera.x, vCamera.y, vCamera.z));
m_msCamera = new CPhysicsMotionState(startTransform, &m_srtCamera);
btScalar tMass(80.7f);
bool isDynamic = (tMass != 0.f);
btVector3 localInertia(0,0,0);
if (isDynamic)
    cameraShape->calculateLocalInertia(tMass,localInertia);
btRigidBody::btRigidBodyConstructionInfo rbInfo(tMass, m_msCamera, cameraShape, localInertia);
m_rigidBody = new btRigidBody(rbInfo);
m_rigidBody->setCollisionFlags(m_rigidBody->getCollisionFlags() |
    btCollisionObject::CF_KINEMATIC_OBJECT);
m_rigidBody->setActivationState(DISABLE_DEACTIVATION);

This is the code in Update() that runs each frame:

CSRTTransform srtCamera = CCameraTask::GetPtr()->GetCamera();
Quaternion qRotate = srtCamera.m_qRotate;
btQuaternion rot = btQuaternion(qRotate.x, qRotate.y, qRotate.z, qRotate.w);
CVector vCamera = CCameraTask::GetPtr()->GetPosition();
btVector3 pos = btVector3(vCamera.x, vCamera.y, vCamera.z);
CPhysicsMotionState* cameraMotionState = CCameraTask::GetPtr()->GetMotionState();
cameraMotionState->setKinematicPos(rot, pos);


texts: Directx11 batching verticies to draw later

texts:
I have several draw functions in my renderer to draw primitives e.g.:

Drawing a Quad:

void Renderer::DrawQuad2D(float left, float bottom, float right, float top, const Rgba& color /*= Rgba::WHITE*/, const Vector4& texCoords /*= Vector4::ZW_AXIS*/) noexcept {
    Vector3 v_lb = Vector3(left, bottom, 0.0f);
    Vector3 v_rt = Vector3(right, top, 0.0f);
    Vector3 v_lt = Vector3(left, top, 0.0f);
    Vector3 v_rb = Vector3(right, bottom, 0.0f);
    Vector2 uv_lt = Vector2(texCoords.x, texCoords.y);
    Vector2 uv_lb = Vector2(texCoords.x, texCoords.w);
    Vector2 uv_rt = Vector2(texCoords.z, texCoords.y);
    Vector2 uv_rb = Vector2(texCoords.z, texCoords.w);
    std::vector<Vertex3D> vbo = {
        Vertex3D(v_lb, color, uv_lb)
        ,Vertex3D(v_lt, color, uv_lt)
        ,Vertex3D(v_rt, color, uv_rt)
        ,Vertex3D(v_rb, color, uv_rb)
    };
    std::vector<unsigned int> ibo = {
        0, 1, 2
        , 0, 2, 3
    };
    DrawIndexed(PrimitiveType::Triangles, vbo, ibo);

}

Sending the verts and indexes to the GPU

void Renderer::DrawIndexed(const PrimitiveType& topology, const std::vector<Vertex3D>& vbo, const std::vector<unsigned int>& ibo) noexcept {
    UpdateVbo(vbo);
    UpdateIbo(ibo);
    DrawIndexed(topology, _temp_vbo.get(), _temp_ibo.get(), ibo.size());
}

Setup and call DrawIndex on immediate context.

void Renderer::DrawIndexed(const PrimitiveType& topology, VertexBuffer* vbo, IndexBuffer* ibo, std::size_t index_count, std::size_t startVertex /*= 0*/, std::size_t baseVertexLocation /*= 0*/) noexcept {
    GUARANTEE_OR_DIE(_current_material, "Attempting to call Draw function without a material set!\n");
    D3D11_PRIMITIVE_TOPOLOGY d3d_prim = PrimitiveTypeToD3dTopology(topology);
    _rhi_context->GetDxContext()->IASetPrimitiveTopology(d3d_prim);
    unsigned int stride = sizeof(VertexBuffer::arraybuffer_t);
    unsigned int offsets = 0;
    ID3D11Buffer* dx_vbo_buffer = vbo->GetDxBuffer();
    ID3D11Buffer* dx_ibo_buffer = ibo->GetDxBuffer();
    _rhi_context->GetDxContext()->IASetVertexBuffers(0, 1, &dx_vbo_buffer, &stride, &offsets);
    _rhi_context->GetDxContext()->IASetIndexBuffer(dx_ibo_buffer, DXGI_FORMAT_R32_UINT, offsets);
    _rhi_context->DrawIndexed(index_count, startVertex, baseVertexLocation);
}

The most noticeable problem is each function issues a draw call. Doing this enough per frame (about 100) causes massive lag. How would I implement a batching such that each of these functions, instead of emitting a draw call immediately, collects all the verts/indexes and doesn't draw until the end of the frame?


texts: How can I find a projectile's launch angle?

texts:
I am making a 2d game in which units fire arrows at each other.
I know the shooter's and the target's position and the initial velocity of the projectile. I want to know the angle the projectile should have in order to land on the target. The target could be at a different height than the shooter.

To sum up I know v0, R and g and I need to find the angle (or the height ?).

I read http://en.wikipedia.org/wiki/Projectile_motion ,but I can't find something related to what I need.


texts: UnrealScript access variable in one class from another?

texts:
So there are some similar questions out there but the responses often say that you should use 'new' or 'spawn', but I'm working with the playercontroller don't want to make a new playercontroller.  Maybe this isn't the right way to be doing this but I want to view the state of a variable in the playercontroller that will change fairly often from my HUD.  Is there a way to do this?

playercontroller class

var bool bYeaNo;

exec function change() {
  bYeaNo= !bYeaNo;
}

defaultproperties
{
  bYeaNo = false
}

HUD class

event PostRender() {
  Super.PostRender();
}

function DrawHUD() {
  Super.DrawHUD();
  Canvas.SetDrawColor(0, 0, 0);
  Canvas.SetPos(25, 25);

  if (bYeaNo) { //this is wrong so what would make this work?
    Canvas.DrawText("Yea");
  } else {
    Canvas.DrawText("No");
  }
}


texts: How do I get the networkId of an object?

texts:
My clients have a way of spawning "defense" barriers and I would like to limit the number of defense barriers per client to 1; A way of doing this is to destroy the old defense (if any) and then spawn the new one. Since this defenses are spawned by the server, how can I tell the server to destroy only the defense that was created by that client?

I guess that by storing the networkID of the spawned defense I can later tell the server to destroy it and repeat. Am I attacking this right?

Having this:

[Command]
void CmdDefenseSpawned(string _playerID, string PlaceToDefenseName, Vector3 toDefense, Quaternion defenseRotation)
{
    Debug.Log("Player " + _playerID + " placed a defense on " + PlaceToDefenseName + " Position= " + toDefense);
    GameObject defenseInstance = Instantiate(defense, toDefense, defenseRotation);
    NetworkServer.Spawn(defenseInstance);
}

I would like something like this:

NetworkInstanceId defenseInstanceNetId = defenseInstance.NetworkIdentity.netID

So I can later delete the object whenever the client wants to spawn it again.


texts: How can I copy or back-calculate definitions for an entire b2World?

texts:
I'm working on a platformer where I'd like to be able to move or copy bodies between multiple Box2D b2Worlds. The desire has cropped up three times now - moving objects between documents in my editor, moving the player between levels in normal game play, and giving the player a preview of a non-trivial projectile they can shoot in the game, which seems to be most accurately done by simulating the world for a few seconds ahead.

It looks like I can make a parallel world the "long way" - for each body in the world, copy the body data back into a def and re-create it, then copy the fixtures on it in the same way, then do the same for joints; re-set all the velocities; and if it's a "move" rather than a "copy" delete the original one.

I was wondering if someone has already written this code (and if so, was it actually a workable design or not?), or if Box2D has some affordance for doing this within its API which I am missing.


texts: Is there a 2D soft-body physics engine for Flash?

texts: I'd like to write a small physics game by using ActionScript, but do not want to write my own physics engine. Does anyone know a ready-to-use 2D soft-body physics engine with a Flash port?


texts: Terrain (mesh) textures in Unity - blurry?

texts:
I've created a 3D mesh in blender which will be used as a terrain in Unity. Additionaly, I created a 900x900 texture which I'd like to apply as material to the mesh. However, unlike with the normal Unity terrain, the material is only blurry/unrecognizable, not matter how many times I repeat the texture/what import settings I set for the texture.

Some googling brought up that it may have to do something with the shader, but I tried many with no results.

current result

texture


texts: How to know which child collider triggered in parent?

texts:
I have parent object with 3 children. Each children has one collider (BoxColliders actually) marked as triggers each one.

I want to know in a OnTriggerEnter on the parent side which collider was hit.

Similar to this question: How can I determine which Trigger is hit?
But for 3D Colliders (not 2d). As you can see in the accepted answer they used  Collider2D.IsTouching but it doesn't seem to exist any analogue method for a 3D Collider

If is not possible, what other solutions are there? What would be the recommended way? I would like to avoid the overhead from methods like CompareTag and SendMessage if possible.

http://answers.unity.com/answers/1206114/view.html


texts: May I distribute a game engine that is based on textbook examples?

texts:
I have purchased several game programming books to start my journey as a game developer. One of them teaches its readers by building a game engine's parts in each chapter until finally you have a complete working game engine. It's bare-bones, but still a game engine.

What exactly am I allowed to do with this engine, as far as releasing an indie game of my own? Is it copyright infringement if I attempt to use the game engine from the book even with my little changes and adjustments?


texts: useful way for coloring 3ds object in opengl

texts:
I have been working in making plane in blender and it has many materials over than 90 , and now
I need it in an opengl project with c++  , but as you know if I but the 3ds file the plane color is totally  white so I have to color back all the parts of the plane and it's getting really hard with all the materials I have , any useful thing I can make ? .


texts: Trouble in 3DS MAX 2016 exported ogre.mesh file refering the correct .material

texts:
Actually we have some trouble in exporting ogre mesh + material files correctly from 3dsmax.
We are using "Easy Ogre Exporter V 2.40" for the export to ogre format.
And actually just testing its features by displaying the images in Cegui-Meshviewer
(http://www.ogre3d.org/tikiwiki/tiki-index.php?page=CEGUI+Mesh+Viewer).

The problem is, the mesh itself refers to a material file, which has added "default" on to it. So for example if we exported "stone.mesh" the exported material would be "stone.material" which is fine. But when inspecting the mesh inside any mesh viewing tool run on ogreengine, the mesh itself is related to a so called "stoneDefault.material" which if I want to get its attributes listed just has no attributes set. But when I inspect the material itself ("stone.material") In those mesh viewers, I can see the correct UV map related to the material and the other attributes fit to what is expected aswell. But the mesh it self seems to be using an non existing "stoneDefault.material" (thats at least the name related to it) And I also checked if it changes anythign when I just change the name of "stone.material" to "stoneDefault.material" But this jsut resaulted in 2 different materials with the same name isnide the viewer.

So my Question is: Is this probably a bug in the viiewers/exporter?
Or am I missing/missunderstanding soemthing?

we selected for testing portability ogre version 1 as exporting file format.


texts: How can I minimise data sent through a network in a modern FPS?

texts: I am aware of snapshot interpolation with the use of delta compression as being a technique used to minimise the amount of data sent in a modern FPS game like Quake 3, but what other techniques are there?


texts: How can I limit the movement angle of a Farseer joint?

texts:
How can I create rectangles in Farseer that behave like the two red rectangles in this video:

https://www.youtube.com/watch?v=w0p2y4dRylQ

I created an angle joint, but it behaves weird. Should I use an angle joint or is it better to use another joint?

In addition, I don't know how to adjust the angle of the joint so that the rectangle only moves in a predefined angle. How can I limit the movement angle of a joint?

I tried it like this, but the rectangle moves not as it should:

       RectangleA1 = BodyFactory.CreateRectangle(world, 3.50f, 0.50f, 1.0f);
       RectangleA1.BodyType = BodyType.Dynamic;
       RectangleA1.Position = new Vector2(10.4f, 5.40f);
       RectangleA1.Rotation = 0f;
       RectangleA1.CollisionCategories = Category.Cat5;

       RectangleA2 = BodyFactory.CreateRectangle(world, 0.10f, 1.00f, 1.0f);
       RectangleA2.BodyType = BodyType.Static;
       RectangleA2.Position = new Vector2(8.6f, 6.2f);
       RectangleA2.Rotation = 0f;
       RectangleA2.CollisionCategories = Category.Cat5;

       AngleJoint1 = JointFactory.CreateAngleJoint(world, RectangleA1, RectangleA2);

       spriteBatch.Draw(RectangleA1Sprite, ConvertUnits.ToDisplayUnits(RectangleA1.Position), null, Color.White, RectangleA1.Rotation, new Vector2(RectangleA1Sprite.Width / 2.0f, RectangleA1Sprite.Height / 2.0f), 1f, SpriteEffects.None, 0f);

       spriteBatch.Draw(RectangleA2Sprite, ConvertUnits.ToDisplayUnits(RectangleA2.Position), null, Color.White, RectangleA2.Rotation, new Vector2(RectangleA2Sprite.Width / 2.0f, RectangleA2Sprite.Height / 2.0f), 1f, SpriteEffects.None, 0f);


texts:
I would like to create a small game about battles in the Middle Ages.
Imagine a procedurally generated 2d map with rivers, fields, and a small castle.
Two sides. One player will attack the castle, and the second player defends it.
The whole game will be with a view - top down. I like this look (and maybe it will simplify the work).
Imagine a player's cannon approaching the castle and attacking it.The cannon fires (e.g., into a tower) and the tower starts to fall apart. How to make this process more interesting? With various effects (for example, to the place where the gun fell off a piece of wall, and on the roof of the tower there was a crack).
I like the process of destruction in AE defenite edition, but it looks the same for all types of buildings (sooner or later they will turn it into the same bunch).
The example what I'm mean when say 2d castle in top down view:
How to break this castle into chips?
P.S I hope you see the author's patron, from his patron this picture could be downloaded for free. He has many other amazing pictures.

ADD some visual guide:
enter image description here


texts: VBO GL_STREAM_DRAW double buffer or new buffer?

texts:
There is some conflicting information on the STREAM usage specifier.

Apple's documentation states you should use double buffering and update the stream buffer that is not being read by the GPU.

OpenGL's reference documentation states you should only modify the contents of the buffer once. Which implies you should create a new buffer to write data instead of reusing the existing buffer.

Is there a reason to use the more complicated double buffering technique?


texts: Changing the color of a sprite at runtime

texts:
Is there a form to change the color of a sprite in runtime?}

I have a black point loaded with an image, but i dont want to load various images with different colors, is there a mode to change the color in runtime and not loading lot of images?

And i want to tell it what part to color of the sprite, is it possible?


texts: I recently released my first game on the Google Play Store (yay!), and a few days later I found my game had been reuploaded to two different shady-looking sites (Softonic and Fibonapps). Needless to say, I did not give either of these sites permission to distribute my game. It is a paid app, so if people download it from these other sites I'm effectively losing money. I sent an email to both about two weeks ago asking them to remove it, I've gotten no response and the listings are still up. How do I proceed from here?


texts: Problems making my basketball bounce around horizontally

texts:
This is probably a very easy question, but I can't seem to understand why it's not working.

I want the basketball to bounce horizontally when it touches the borders on the right and left, but when it bounces on the right, it seems to go just a little bit further than it should.

Any suggestions?

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    basketballPosition.X += ballSpeed;
    if (basketballPosition.X > Window.ClientBounds.Width - basketball.Width || basketballPosition.X < 0)
    {
        ballSpeed *= -1;
    }

    base.Update(gameTime);
}

And my Draw method:

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();

        spriteBatch.Draw(basketball,
                         basketballPosition,
                         null,
                         Color.White,
                         0,
                         Vector2.Zero,
                         1.5f,
                         SpriteEffects.None,
                         0);

        spriteBatch.End();

        base.Draw(gameTime);
    }

Edit The problem was I was using a scale of 1.5f for drawing the image. Can someone explain how I would get the true border of the image if I were using scale? It seems the border stay as the original size, but the texture is drawn to whatever scale I choose.


texts: Where do I start if I want to make music and audio for video games?

texts:
I am a singer/songwriter/instrumentalist, as well as a video game lover. I have some basis in informatics but I have spent 1000x the time on music in comparison with programming. I came to think that making music and audio for video games could be a great way to make money while making something exciting. I dream of making my own game someday, and I thought that starting by making what I do best (music and audio) could make me discover the universe of game development, while giving me the opportunity to work on something that makes sense to me.

I can make many kinds of music and my vocal skills make it easier to create audio for games (beast sounds, animal sounds, human sounds, and so on). That said, I could tell this and that, but having credibility is very hard since no one knows how I sound. Where do I start? And how do I contact people that are seeking the kind of service that I offer?

I have almost 20 years of experience as a singer, 11 as a songwriter and 5 as an instrumentalist. I can use software to program audio performances, and I have professional quality microphone (Audio Technica 4050) and audio interface. I have all the equipment and the softwares (Pro Tools) necessary to record music and audio for video game.


texts: How to architect collision detection in SFML

texts:
I have a pretty simple game engine that I'm making for a 2d platformer game. I don't want it to be super advanced, but it does have some basic properties. Most important to this question is a class called Entity. Entities are basically just objects in the game that are drawn to the screen and move around. They all have a square bounding box aroud them. Each different entity inherits from the class Entity (ex. Player and Ground inherit from Entity).

I want a nice, object oriented way to handle collisions between different entities. I'd like to be able to write rules of what happens when two things collide in such a way that I don't have to do a ton of casts or rewrite a lot of code. I was thinking of doing something like

class Entity {
    public:
        void collide(Entity* ent);
}

But I'm not sure how I would go about getting the type of the argument. Any suggestions on what to do?


texts: Fragment shader compiling in webGL but not in OpenGL

texts:
I am programming in Haxe (language compiling to multiple platforms) and I have written some shaders.

My fragment shader runs fine in html5, but when I try to compile for native (OS X and/or Neko, a VM for Haxe) I get a shader compilation error, but no details (I am using lime which is a platform abstraction that does these things for me).

Here is the shader:

precision mediump float;

varying vec4 v_color;

void main() {
    gl_FragColor = v_color;
}

Very simple as you can see. It runs fine in webGL, but it seems it won't compile in OpenGL. I am no expert in shaders so I have no idea what might be wrong. Am I using some syntax that only exists in webGL?

Also just in case, here is my vertex shader (which compiles fine):

attribute vec3 a_position;
attribute vec4 a_color;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;

varying vec4 v_color;

void main() {
    gl_Position = uMVMatrix * vec4(a_position, 1);
    v_color = a_color;
}


texts: I cannot save my game data on Godot Engine

texts:
I'm trying to save my game on Godot Engine by pressing a "save" button but I get this message error when i do:

  Attempt to call function 'get_nodes_in_group' in base 'null instance' on a null instance

this is my project code:

#File.gd, contains the methods to write and read over the file
extends Node

var path_name := "res://resource/debug/save"
var file := "sav.tres"

class_name WriterReader

func write():
    var writer := Save.new()
    var directory := Directory.new()

    writer.version = ProjectSettings.get_setting("application/config/Version")
    for node in get_tree().get_nodes_in_group("persistance"): #it's  the line that thows the error
        node.save(writer)
    print(writer.version)

    if not directory.dir_exists(path_name):
        directory.make_dir_recursive(path_name)

    if ResourceSaver.save(path_name.plus_file(file), writer) != OK:
        print("ERROR")

#the save button gdscript file
extends Button

func _ready():
    var save = Save.new()
    self.connect("pressed", self, "save_game", [save])

func save_game(save):
    var s = WriterReader.new()
    s.write()

#it's the part of code where of the player character is saving
extends KinematicBody2D
...

func save(write: Resource):
    write.dat = {"position": position, "health": health}

#sav.gd, singleton used to save the player data

extends Resource

class_name Save

var dat : Dictionary = {}
var version := ""

I'm a beginner on Godot so I cannot figure out why this happens.

could somebody explain me, please?

Thanks


texts: Recording Xbox controller button presses?

texts:
I would like to generate some sort of log file of xbox gamepad events while playing an existing game on PC, such as Call of Duty.

I am not developing a game necessarily, I just would like a static file of all button presses recorded during a session of gameplay. I am writing an application that will use this data as input.

Can anyone recommend any software tools that could enable me to do this? Thanks in advance.

I have Mac, Windows, and Ubuntu that I can use.


texts: Switch axes and handedness of a quaternion?

texts:
I have a quaternion, coming from a system with the following:(intertial sensor)

Right handed.
Forward direction: Y axis
Right direction: X axis
Up direction: Z axis

I need to convert this into a coordinate system that is: (Unreal engine)

left-handed.
Forward direction: X axis
Right direction: Y axis
Up direction: Z axis

I have tried negating the axis, and angle, I have tried switching values, i cannot get this to work. All help greatly appreciated! I am working in C#, with Microsoft.Xna.Quaternion.


texts:
I am currently making a board game and cannot seem to find any vector world map creators where I can select a region of the world to capture and have it download that section. I just want a base map so no city names and preferably no borders.

The map doesn't have to be vector if it is of good enough quality.


texts:
I think that the animation curves in Unity lack the fact of being configurable because they are only chosen with a certain type (no sinusoidal function) and adjustable with handles.

How in C # create an animation (tanslation, rotation, scale) so as, for a selected mesh, to introduce parameters of a chosen mathematical function and any corresponding, if it is a translation for example, to x_position, y_position and z_position in function of the time variable?

thank you !

What if I now need to define time intervals?
for example:

a function f1 on [0.20]

a function f2 on [20.50]

The most difficult is to convert by the correct Time.time factor so that the real time varies well in seconds within the limits defined by each of these intervals.

thanks


texts: When or why would someone use a programming language (Swift, Java, C++, Rust etc...) over an engine like Unity?

texts: Everytime I've read about people asking whether they should write their game in C++ or Unity, Unity is usually the default answer, unless they want to go through the hassle of creating an engine by themselves when Unity already does everything for you.  If that's the case is there ever a case where writing a game in C++, Java, Rust etc... is better than using Unity? If so what are these cases?


texts:
So how would I design a replay system?

You may know it from certain games like Warcraft 3 or Starcraft where you can watch the game again after it has been played already.

You end up with a relatively small replay file. So my questions are:

How to save the data? (custom format?) (small filesize)
What shall be saved?
How to make it generic so it can be used in other games to record a time period (and not a complete match for example)?
Make it possible to forward and rewind (WC3 couldn't rewind as far as I remember)


texts: Unity 2D game object moving up in curve?

texts: How can I make a rigidbody2d game object moving up curve like the attached screenshot?


texts: How do I add a third axis of movement for my character to go up and down?

texts:
My movement system at the moment is based off of a tutorial I followed. The tutorial is about moving with spherical gravity. I want to add another axis of movement so my character can fly up and down with jet propulsion, but I cant get it to work, here is a couple parts of the tutorial code below:
void Update()
    {
        Vector2 playerInput;
        playerInput.x = Input.GetAxis("Horizontal");
        playerInput.y = Input.GetAxis("Vertical");
        playerInput = Vector2.ClampMagnitude(playerInput, 1f);

        if (playerInputSpace)
        {
            rightAxis = ProjectDirectionOnPlane(playerInputSpace.right, upAxis);
            forwardAxis =
                ProjectDirectionOnPlane(playerInputSpace.forward, upAxis);
        }
        else
        {
            rightAxis = ProjectDirectionOnPlane(Vector3.right, upAxis);
            forwardAxis = ProjectDirectionOnPlane(Vector3.forward, upAxis);
        }
        desiredVelocity =
            new Vector3(playerInput.x, 0f, playerInput.y) * maxSpeed;

        desiredJump |= Input.GetButtonDown("Jump");

        transform.rotation = Quaternion.LookRotation(forwardAxis, upAxis);

    }

...

void AdjustVelocity()
    {
        Vector3 xAxis = ProjectDirectionOnPlane(rightAxis, contactNormal);
        Vector3 zAxis = ProjectDirectionOnPlane(forwardAxis, contactNormal);

        float currentX = Vector3.Dot(velocity, xAxis);
        float currentZ = Vector3.Dot(velocity, zAxis);

        float acceleration = OnGround ? maxAcceleration : maxAirAcceleration;
        float maxSpeedChange = acceleration * Time.deltaTime;

        float newX =
            Mathf.MoveTowards(currentX, desiredVelocity.x, maxSpeedChange);
        float newZ =
            Mathf.MoveTowards(currentZ, desiredVelocity.z, maxSpeedChange);

        velocity += xAxis * (newX - currentX) + zAxis * (newZ - currentZ);
    }

How can I add another axis? I already have a third axis control for the trigger buttons set up in the input project settings, but I just cant find a way to fit a rising and falling axis in here. Help would be much appreciated


texts: Find required entities to accomplish specific task in shortest time

texts:
I have a grid like map with entities that can perform turn-based actions like moving or growing strength. When I have a task that requires a certain strength, I want to find the entities required to solve that task as fast as possible and move them to the target.

The distance to the target is important, since moving a tile takes 1 turn. When entities move on a tile with an existing entity, their strength is combined together. A task can be solved only if the combined strength of the last entity is greater than the requirement. This logically means that entities near the target can grow while additional entities need to move to the target immediately.

It feels like I could use a modified pathfinding, but I can't formulate the procedure to get something meaningful. This inablity also worries me a bit that the problem might be np-hard.

Can you help me?


texts: GameTime Replacement / Wrapper for Pausing , Slow-mo and 'Fast-mo'

texts:
I'm looking to change the way in which my game uses GameTime to run the game so that I can easily pause the game (elapsedTime = 0) or change how slow/fast the in game elements interact as a scaler of the actual time passed (elapsedTime *= timeScale).

In my project, I always make the assumption that the game is not running on a fixed time step for a number of reasons. Due to this, any changes of states have the elapsed time factored in from GameTime. I'm hoping this means I can simply simulate slow-mo, fast-mo, force short freezes (like when you kill an enemy in TLoZ: Windwaker - there's a short pause for emphasis) or pause the game by interfering with the GameTime.ElapsedGameTime that all of my Update() code uses.

My first thought is to stop using GameTime within any update code, and to instead wrap a new class (MyTime) around GameTime.

MyTime would do the following:

Seperates real time and game time. Real time is the passage of time outside of the system. Game time is the passage of time within the game's world, i.e if slow motion is in effect, the time passed within the game would be lower for the period of slow motion.
Time scaling can either be started and ended, or requested to be active for a length of real time or game time.
Time can be paused or frozen with either manual start and stop calls, or for a length of time, again based on either real or game time.

Based on this discussion, where it's states that GameTime is recreated every tick within XNA's base Game class, I'm hestitant to just store a reference to GameTime within MyTime as I personally don't know how GameTime is altered. I also don't know the 'best' way to retrieve the GameTime reference in the first place, the reference is available within the Update() and Draw() calls, however since gameTime isn't made available throughout any derived from Game class, it's implied taking the gameTime reference out of those update and draw calls isn't intended.

Is my intended implementation of this the right way of achieveing this system? What is a good to expose GameTime to MyTime? Should I implement my own way to track time and not rely on GameTime at all?


texts: Unity procedural mesh with different colours/texture per layer

texts:
I'm generating a procedural mesh, which is a 9x9 grid of cubes. I've written it so that none of the internal faces are rendered, until a cube above it has been removed, at which point the new faces are added. Think Minecraft voxels.
What I'd like to do is to have a texture over the entire outside of the cube, and then for each layer of the cube down towards its centre, have a different colour.
So the outside would have some arbitrary texture, and when a hole is punched in it, it shows a green cube beneath, and then a yellow cube beneath that, and so on down.
Or alternatively, use a single texture, with different coloured areas on it.  Then depending on the faces distance from the centre of the mesh, use a different section of the texture.   So update the UV mapping for the given face.
Is this something that is best achieved with a customer shader, or can anyone suggest another way of doing this?
Thanks


texts: Rectangles clear each other when moving on canvas

texts:
I am having this problem after moving rectangles, they seem to delete one another.
Most probably it is a problem with clearRect(...) method.
This is the clean function I am using:

clean: function(element){
        // All default values clean all the screen
        if(typeof element.x === 'undefined'){
            element.x = 0;
        }

        if(typeof element.y === 'undefined'){
            element.y = 0;
        }

        if(typeof element.width === 'undefined'){
            element.width = canvas.width;
        }

        if(typeof element.height === 'undefined'){
            element.height = canvas.height;
        }

        // In case values are entered
        if(element.type === 'rectangle'){
            ctx.clearRect(element.x,element.y,element.width,element.height);
        }
    }

This is the rendering

rect: function(element){
    // Check if color is defined
    if(typeof element.color === 'undefined'){
        element.color = 'black';
    }
    else{
        ctx.fillStyle = element.color;
    }

    // Draw the rectangle
    ctx.fillRect(element.x,element.y,element.width,element.height);
}


texts: Momentum and order of update problems in my physics engine

texts:
This question is a "follow-up" question from my previous one, regarding collision detection and resolution, which you can find here.

If you don't want to read the previous question, here's a brief description on how my physics engine works:

Every physical entity is stored in a class called SSSPBody.
Only AABBs are supported.
Every SSSPBody is stored in a class called SSSPWorld, which updates every body and handles gravity.
Every frame, SSSPWorld updates every body.
Every updated body looks for nearby bodies in a spatial hash, checks if they need to detect collisions with them. If yes, they invoke a "collision" event and check if they need to resolve collisions with them. If yes, they calculate the penetration vector and directional overlap, then change their position in order to resolve the penetration.
When a body collides with another, it transfers its velocity to the other one by simply setting the body's velocity to its own.
A body is velocity is set to 0 when it hasn't changed position from the last frame. If it also collides with a moving body (such as a lift or a moving platforms) it calculates the movement difference of the lift to see if the body hasn't moved from its last position.
Also, a body invokes a "crushed" event when all its AABB corners overlapped something in a frame.

This is the FULL source code of my game. It's divided in three projects. SFMLStart is a simple library handling input, drawing and updating of entities. SFMLStartPhysics is the most important one, where the SSSPBody and SSSPWorld classes are. PlatformerPhysicsTest is the game project, containing all the game logic.
And this is the "update" method in the SSSPBody class, commented and simplified. You can take a look only at this if you don't feel like looking at the whole SFMLStartSimplePhysics project. (And even if you do, you should still take a look at this since it's commented.)

The .gif shows two problems.

If bodies are placed in a different order, different results happen. The crates on the left are identical to the crates on the right, only placed in the inverse order (in the editor).
Both crates should be propelled towards the top of the screen. In the situation on the left, no crates are propelled. On the right, only one of them is. Both situations are unintended.

First problem: order of update
This is fairly simple to understand. In the situation on the left, the topmost crate is updated before the other one. Even if the crate on the bottom "transfers" velocity to the other one, it needs to wait the next frame to move. Since it didn't move, the bottom crate's velocity is set to 0.
I don't have any idea how to fix this. I'd prefer the solution to not be dependent on "sorting" the update list, because I feel I'm doing something wrong in the whole physics engine design.
How do the major physics engines (Box2D, Bullet, Chipmunk) handle the update order?

Second problem: only one crate is propelled towards the ceiling
I yet don't understand why this happens. What the "spring" entity does is set the body's velocity to -4000 and re-position it on top of the spring itself. Even if I disable the re-positioning code, the problem still occurs.
My idea is that when the bottom crate collides with the top crate, its velocity is set to 0. I'm not sure why this happens.

Despite the chance of looking like someone who gives up at the first problem, I posted the whole project source code above. I don't have anything to prove it, but believe me, I tried hard to fix this but I just couldn't find a solution and I don't have any previous experience with physics and collisions. I've been trying to solve these two problems for more than a week and now I'm desperate.
I don't think I can find a solution on my own without stripping many features out of the game (velocity transfer and springs, for example).
Thanks a lot for the time spent reading this question, and thanks even more if you even try coming up with a solution or a suggestion.


texts: How to implement behavior in a component-based game architecture?

texts:
I am starting to implement player and enemy AI in a game, but I am confused about how to best implement this in a component-based game architecture.

Say I have a following player character that can be stationary, running and swinging a sword. A player can transit to the swing sword state from both the stationary and running state, but then the swing must be completed before the player can resume standing or running around. During the swing, the player cannot walk around.

As I see it, I have two implementation approaches:

Create a single AI-component containing all player logic (either decoupled from the actual component or embedded as a PlayerAIComponent). I can easily how to enforce the state restrictions without creating coupling between individual components making up the player entity. However, the AI-component cannot be broken up. If I have, for example, an enemy that can only stand and walk around or only walks around and occasionally swing a sword, I have to create new AI-components.
Break the behavior up in components, each identifying a specific state. I then get a StandComponent, WalkComponent and SwingComponent. To enforce the transition rules, I have to couple each component. SwingComponent must disable StandComponent and WalkComponent for the duration of the swing. When I have an enemy that only stands around, swinging a sword occasionally, I have to make sure SwingComponent only disables WalkComponent if it is present. Although this allows for better mix-and-matching components, it can lead to a maintainability nightmare as each time a dependency is added, the existing components must be updated to play nicely with the new requirements the dependency places on the character.

The ideal situation would be that a designer can build new enemies/players by dragging components into a container, without having to touch a single line of engine or script code. Although I am not sure script coding can be avoided, I want to keep it as simple as possible.

Summing it all up: Should I lob all AI logic into one component or break up each logic state into separate components to create entity variants more easily?

edit: I suspect there is some confusion about what I meant with the first and second situation. I have tried to explain it in the diagram below.

Note the relationship between the individual states and the entity. In the first situation, an AI component is pre-built before being put in the entity. A designer can only select from a distinct set of AIComponents made available by the programmer. The second situation has the different states on the same level as other components. A designer can now create an entity with unique AI without interference of a programmer.

The question is, are these the only two options for structuring AI in an component-based entity and, if so, what would give the maximum flexibility?


texts: How to convert a premade mesh into voxels so I can use algorithms such as marching cubes

texts:
I have a mesh that was created in a 3D program which is the terrain the player will walk on.  I want to allow the terrain to be deformable by the player, but for it to be smooth (not like Minecraft).

From what I have read from existing questions similar to mine, I need to use an algorithm such as Marching Cubes (which I don't understand yet).  From what I understand, those types of algorithms are suited for procedural generation.

My question is;  How do I convert my mesh into voxels so that I can use algorithms such as Marching cubes?

Is it simply a matter of cutting up my mesh in chunks?

If it helps, I will be using C# and Unity 3D.


texts:
There is this strange issue with the collision in a game I am making. When the player is slightly lower than a block it is colliding with from the side, the player ends up clipping to the top of the block rather than sliding along the side of it down. Do you have an idea how to fix it?

If that description didn't help you at all you can reproduce it here (goes to the website with the game on it). (Use WASD/Space/Arrow Keys to move) To reproduce, stand on the single block and hold the right move button. You will fall off the edge, hit the side of the block, and get clipped to the top of it. You are meant to fall onto the block below instead.
(The words and colors are debug info)

The code below is what handles the collision detection. If you need the rest of the code, you can view the source of the page linked above.

this.doCollision = function() {
var tx = Math.floor(this.x),
    ty = Math.floor(this.y),
    nx = this.x % 1,
    ny = this.y % 1,
    cell = this.cell = levelStorage.currentLevel.getTileAtPosition(tx, ty),
    cellRight = this.cellRight = levelStorage.currentLevel.getTileAtPosition(tx + 1, ty),
    cellDown = this.cellDown = levelStorage.currentLevel.getTileAtPosition(tx, ty + 1),
    cellDiag = this.cellDiag = levelStorage.currentLevel.getTileAtPosition(tx + 1, ty + 1);

if(this.vy > 0) { // Ground collision
// The !cell checks return if the cell exists or not (null)
  if((cellDown && !cell) || (!cellRight && cellDiag && nx)) {
    this.y = ty;
    this.vy = 0;
    this.falling = false;
    this.jumping = false;
    ny = 0
  }
}else
if(this.vy < 0) { // Ceiling collision
  if((!cellDown && cell) || (cellRight && !cellDiag && nx)) {
    this.y = ty + 1;
    this.vy = 0;
    cell = this.cell = cellDown;
    cellRight = this.cellRight = cellDiag;
    ny = 0;
  }
}
if(this.vx > 0) { // Right collision
  if((cellRight && !cell) || (!cellDown && cellDiag && ny)) {
    this.x = tx;
    this.vx = 0;
    nx = 0;
  }
}else
if(this.vx < 0) { // Left collision
  if((!cellRight && cell) || (cellDown && !cellDiag && ny)) {
    this.x = tx + 1;
    this.vx = 0;
    cell = this.cell = cellRight;
    cellDown = this.cellDown = cellDiag;
    nx = 0;
  }
}
this.falling = !(cellDown || (nx && cellDiag)); // If player isn't on ground
}
}

Thanks for the help!

EDIT: I should note this also happens with the bottom of blocks as well. The same principles apply as clipping to the top, except you clip to the bottom instead.


texts: Object pools for efficient resource management

texts:
How can I avoid using default new() to create each object?

My previous demo had very unpleasant framerate hiccups during dynamic memory allocations (usually, when arrays are resized), and creating lots of small objects which often contain one pointer to some DirectX resource seems like an awful lot of waste.

I'm thinking about:

Creating a master look-up table to refer to objects by handles (for safety & ease of serialization), much like EntityList in source engine
Creating a templated object pool, which will store items contiguously (more cache-friendly, fast iteration, etc.) and the stored elements will be accessed (by external systems) via the global lookup table.

The object pool will use the swap-with-last trick for fast removal (it will invoke the object's ~destructor first) and will update the corresponding indices in the global table accordingly (when growing/shrinking/moving elements). The elements will be copied via plain memcpy().

Is it a good idea? Will it be safe to store objects of non-POD types (e.g. pointers, vtable) in such containers?

Related post: Dynamic Memory Allocation and Memory Management


texts: how to make a continuous machine gun sound-effect

texts:
I am trying to make an entity fire one or more machine-guns.

For each gun I store the time between shots (1.0 / firing rate) and the time since the last shot.

Also I've loaded ~10 different gun-shot sound-effects.

Now, for each gun I do the following:

function update(deltatime):
    timeSinceLastShot += deltatime

    if timeSinceLastShot >= timeBetweenShots + verySmallRandomValue():
        timeSinceLastShot -= timeBetweenShots

        if gunIsFiring:
            displayMuzzleFlash()
            spawnBullet()
            selectRandomSound().play()

But now I often get a crackling noise (which I assume is when two or more guns are firing at the same time and confuse the sound-device).

My question is whether

A) This a common problem and there is a well-known solution, maybe to do with the channels or something, or

B) I am using a completely wrong approach to the task. I had a look at some sound-assets for other games and they used complete burst with multiple shots. I suppose I could try that, but I would like to have organic little hickups in the gun-fire (that's what the random value is for) to make the game more gritty and dirty.

I am using Panda3D, but I had the exact same problem in PyGame and SDL.

[edit]

Thanks a lot for the answers so far! One more problem with faking it though: Now how do I stop the sound? Let's say I have an effect with 5 bangs...

*bang* *bang* *bang* *bang* *bang*

And I magically manage to loop it so that there's no gap or overlap if the player fires more than 5 shots. Now, what do I do if the player stops firing halfway through the third bang? How do I know how long to keep playing the sample so that the third bang is completed and I can start playing the rumbling echo of the last shot?

Of course I can look up the shot/pause timing of that sound-sample and code accordingly, but it feels extremely hacky.


texts:
I have been teaching myself the OpenGL library for a while now, and want to start making a game. However, for an easier introduction, I want to start with something 2D, such as a top down Pokemon-style game.

Is this a good plan, or is OpenGL made specifically for 3D?


texts: Apply a grain effect to all the elements of a level

texts:
I'm currently experimenting a little bit on level design. Let's say that I've a room composed of walls and a floor tiles. I'd like to apply to all these elements a sort of "grain" effect, similar to concrete.  I wonder which is the better way to go... the only think I can immagine is working with texture directly, so for each element create the texture that already contains the "grain" effect.

I've also tried to apply a generic screen shader but the result is not good because the grain is fixed to the screen, I wanted it to be fixed to walls/floor. Obviously creating all the textures is a long process and I have to keep UV absolutelly proportional for each element.

I'm ok with that solution actually but I wonder if there is anyother way to apply this effect all in once in a simpler and "safer" way, soemthing like a decal that maybe adds also some imperfections.


texts: Fastest way to neutralize scale in the transform matrix?

texts:
Let's assume we have 4x4 3D transformation matrix, that is the result of scale, rotation, and translation transforms. How to set its scale to (1,1,1) in the fastest way? Assume also that the matrix is represented by float[16] array.

By fastest way I mean, the most performance accurate way, that will be low CPU cost.


texts: How can I create a "see behind walls" effect?

texts:
Divinity: Original Sin 2 has a beautiful see-through system. When I go behind walls, a splash mask will appear, and when I move around the game, it changes. It's like a dissolve shader, and has a metaball effect.

How can I replicate this effect, creating a dynamic splash mask when players go behind walls?

You can see the desired effect in motion via this YouTube video.


texts: Using indices in obj files and handling normals

texts:
I have been loading obj files and using indices for handling duplicated vector positions, but I have not gotten to the point of requiring normal data to be passed to the shaders as well.

The problem I have is that obj files store the relevant normal data in the face field, and when it comes to loading a point that is used multiple times, the normal might be different for each subsequent face including a particular vertex, but I can only pass one normal per vertex.

How would people suggest getting around this issue?

I can only think of two ways, either stop using indices and that will allow me to pass unique position vector / normal pairings, or store all instances of position/normal pairs and if a new normal is required for a position, create it and index it accordingly.


texts: Reset 3ds Max 2017 keyboard shortcuts to default

texts:
I somehow messed up my keyboard shortcuts for 3ds Max 2017. How can I restore them to the default? Is there a default shortcut file I can restore them with?

I'm aware there's a Reset button inside the Keyboard options, but my 3ds Max crashes when I hit that button.


texts:
I'm writing a BSP viewer for a university project. So far I have the main geometry loaded properly, and the PVS working.

Now I'm trying to apply the lightmaps, but I can't seem to get the texture coordinates for the lightmaps calculated properly.

According to here: http://developer.valvesoftware.com/wiki/The_Source_Engine_BSP_File_Format

struct texinfo_t
{
    float textureVecs[2][4];  // [s/t][xyz offset]
    float lightmapVecs[2][4]; // [s/t][xyz offset] - length is in units of texels/area
    int flags;                // miptex flags overrides
    int texdata;               // Pointer to texture name, size, etc.
}

  The first array of floats is in
  essence two vectors that represent how
  the texture is orientated and scaled
  when rendered on the world geometry.
  The two vectors, s and t, are the
  mapping of the left-to-right and
  down-to-up directions in the texture
  pixel coordinate space, onto the
  world. Each vector has an x, y, and z
  component, plus an offset which is the
  "shift" of the texture in that
  direction relative to the world. The
  length of the vectors represent the
  scaling of the texture in each
  direction.

  The 2D coordinates (u, v) of a texture
  pixel (or texel) are mapped to the
  world coordinates (x, y, z) of a point
  on a face by:

  u = tv0,0 * x + tv0,1 * y + tv0,2 * z
  + tv0,3

  v = tv1,0 * x + tv1,1 * y + tv1,2 * z
  + tv1,3

  (ie. The dot product of the vectors
  with the vertex plus the offset in
  that direction. Where tvA,B is
  textureVecs[A][B].

  Furthermore, after calculating (u, v),
  to convert them to texture coordinates
  which you would send to your graphics
  card, divide u and v by the width and
  height of the texture respectively.

So I am doing the calculation as follows. Take the dot product of the vertex and the lightmap vector(lightmapVecs[0][0], lightmapVecs0, lightmapVecs[0][2]) add the offset (lightmapVecs[0][3]), subtract the mins, and divide the result by the width/height.

float s = Vector3f.dot(v, new Vector3f(lightmapVecs[0][0], lightmapVecs[0][1], lightmapVecs[0][2])) + lightmapVecs[0][3] - f.LightmapTextureMinsInLuxels[0];
float t = Vector3f.dot(v, new Vector3f(lightmapVecs[1][0], lightmapVecs[1][1], lightmapVecs[1][2])) + lightmapVecs[1][3] - f.LightmapTextureMinsInLuxels[1];
s /= (f.LightmapTextureSizeInLuxels[0] + 1);
t /= (f.LightmapTextureSizeInLuxels[1] + 1);

However it ends up looking like this:

Here's a sample calculation for the texture coord 't' for one vertex.

vertex = 352.0, -144.00027, -224.0
lightmap vector = -4, 0, 0
lightmap offset = 0
lightmap mins = 9
lightmap height = 14

So the dot product is -1408

(-1408 + 0 - 9) / 14

t = -101.21

This seems way off.


texts: Transforming Position in y-axis (going down) in Unity

texts:
I want the gameobject to go down (position.y) after pressing a key instead of pressing the key repeatedly. So in my current code the object goes down(0.05f) each time I press a key. But I want it to go down (1.2) with a smooth animation when I press a key.

Vector2 Pos;

void Update ()
{
 Pos = transform.position;

 if(Input.anyKeyDown)
 {
   ChangePosY();
 }
 transform.position = Pos;
}

void ChangePosY()
{
 if (Pos.y >= 1.2)
 {
  Pos.y -= 0.05f;
 }
}


texts: the object of type 'GameObject' has been destroyed but you are still trying to acess it

texts:
the object of type 'GameObject' has been destroyed but you are still trying to access it .your script should either check if it is null or you should not destroy the object

my script is in c#

    w = brick[0].GetComponent<SpriteRenderer>().bounds.size.x;
    h = brick[0].GetComponent<SpriteRenderer>().bounds.size.y;
    x = brick[0].transform.position.x - w/2;
    y = brick[0].transform.position.y - h/2;
    xp = ball.transform.position.x;
    yp = ball.transform.position.y;
    if (ptobcollision(x,y, w, h, xp, yp)) {
        ball.GetComponent<Ball>().YDirection = 1;
        //Debug.LogError("now Error");
        Destroy(brick[0]);
    }


texts: Endless 2d runner with increasing speed, how to adjust jump behavior?

texts:
I am making an endless 2d runner with unity. my player object is not moving at all, i move all the other game objects. I have a SpeedManager script which increases the "speed" at every update by a short amount. The movement speed of every gameObject which is streaming towards the player is now multiplied with the SpeedManager "speed".

One controll of my player is a jump. Currently i am using

  public Vector2 jumpForce = new Vector2(0, 350);
  rigidbody2D.AddForce(jumpForce);

The problem now is, as the game goes on, the game objects pass faster and faster but the player jump remains the same. What i want is a jump that goes as far as before, which means, the player should jump faster into the air, reach the same height and drop faster to the ground, so the jump distance is the same.

I tried some stuff like multiplying both the jumpForce.y and the gravity of my player object with my SpeedManager.speed, but i did not achieve anything yet. :)

Greetings.


texts: Can I run into legal issues with random names?

texts:
I'm currently building a game whose NPC's are going to be assigned a random gender and a random name for the right gender. To do this I will be using a "database" of names (actually a text file with  tuples). There would also be a list of last names, which will be added to the first name also randomly.

My question is the following. Suppose one such random name is "George Bush", and this person has been randomly assigned the job of president. As you can see, this could easily be seen as having been "copied" from a real-life person.

The main issue is this. Names will be randomly-generated, yes, but the seed for random-number generation will be constant. In other words, the name of an NPC would be randomly-generated, i.e. I wouldn't choose it, but it would be the same for every player. Could this get me in trouble? We cannot verify all possible names, since the generated number of NPC's could be potentially limitless (new NPC's are being created whenever needed).


texts: Need ideas for an algorithm to draw irregular blotchy shapes

texts: I'm looking to draw irregular shapes on an x,y grid, and I'd like to come up with a simple, fast method if possible.  My only idea so far is to draw a bunch of circles of random sizes very near each other, but at a random distance apart from a more or less central coordinate, then fill in any blank spaces.  I realize this is a clunky, inelegant method, hopefully it will give you a rough idea of the kinds of rounded, random blotchy shapesI'm shooting for.  Please suggest methods to accomplish this, I'm not so much interested in code.  I can noodle that part out myself. Thanks!


texts:
Hi guys i just started using unity recently but today after working on some animation blending, most (not all) prefabs changed to look like this:

What's the cause, and how can i fix it? i tried creating a new project then copied my Asset directory to it but still. also when i try importing a new character i still see the same.

Material structure.


texts: Can DrawIndexedPrimitives() be used for drawing a loaded model mesh-wise?

texts:
I am using DrawIndexedPrimitives() for drawing a loaded 3D model by drawing each mesh part, but this process makes my application very slow. This is perhaps because of a very large number of vertex/index buffer data created in video memory.

That is why I am looking for a way to use the same method for each model mesh instead. The problem is that I don't know how I will set the textures of that mesh. Can anyone offer me some guidance?


texts: How to do Colored Lights in CIE XYZ/LUV-like Space?

texts:
I've a 2d background, some sprites, blitted onto it. And over all that in the final pass I draw colored lights, to make projectiles look cooler. Basically I apply a classic lightmap, which is colored in the process of blitting.

With RGB I used simple, but incorrect code:

//dr,dg,db - source before highlight
//e = light energy
//lr,lg,lb - color filter applied to the light energy
ResultColor = RGB(lighten(dr,e*lr),lighten(dg,e*lg),lighten(db,e*lb));

//light energy divisor (0x100*4*32)
#define EDIV 15
uint8_t lighten(int t, int e) {
  return clamp_byte(t + ((t*e)>>EDIV));
}

Now in CIE-style spaces, instead of RGB, we have luminance coordinate (L in LUV, or Y in XYZ), and two chroma coords, picking the chroma inside the color triangle.

Calculating light in CIE appears to be simple, it is just:

result_light = dst_light*incoming_light

But what about XZ or UV? I tried doing simple averaging:

result_x = 0.5*dx + 0.5*lx;
result_z = 0.5*dz + 0.5*lz;

but it gave too bland of a result, compared to the original RGB color-filter:

Maybe instead of taking 0.5, these weights should depend on the light component somehow? If so, what is the proper matrix? I'm sure it can exist, because the transform from CIE XYZ to RGB is linear.


texts: Video playback on mobile: can't seek to the end

texts:
My Unity3D game needs to play videos on mobile devices (using Handheld.PlayFullscreenMovie()). Seeking works badly. If I tap the video progress bar near the end (expecting it to play the last second then finish), playback jumps back a full 10-20 seconds, depending on the video. What should I try to make it easier for the player to seek within the file? Force additional key frames?

I'm currently encoding with HandbrakeCLI and the following settings:

--preset="AppleTV" --x264-tune=animation --x264-preset=veryslow


texts: Unity's new Input system does not work after building the game

texts:
I've made a test project to test the new Input system pointers (touch and mouse), in the editor, everything works perfectly however when I build the game they don't. it's like there is not an input system. I'm not sure if I'm missing a setting or something.

I've made simple sean where the Ui displays the available devices, whether they're enabled or not, and if a touch or mouse click detected it will display general information about it.

this is how it works in the editor:

And this is the android version, note that button press still works:

I did not record the PC standalone version but it still does not respond.

this is the link to the build:
https://github.com/Venay/Input_test

this is the code I used and couple of screenshots of my settings:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;

namespace Testing.InputDebugger
{
    public class InputDebugger : MonoBehaviour
    {
        PointerInput pointerInput;
        public Text inputText;
        public Text deviceText;
        public Text buttonText;

        private void Awake()
        {
            pointerInput = new PointerInput();
            pointerInput.General.Pointer.performed += ctx => OnPointer(ctx.ReadValue<myCompositData>());
            pointerInput.General.Pointer.canceled += ctx => OnPointer(ctx.ReadValue<myCompositData>());

            string text = "";

            foreach (var S in InputSystem.devices)
            {
                text += S.device + " : " + S.enabled + "  \n";
            }
            deviceText.text = text;
        }

        private void OnEnable() => pointerInput.Enable();
        private void OnDisable() => pointerInput.Disable();

        public void OnPointer(myCompositData data)
        {

            string n = "\n";
            string Press = "Press: " + data.Press.ToString() + n;
            string PressCount = "Press Count: " + data.PressCount + n;
            string Position = "Position: " + data.Position + n;
            string Delta = "Delta: " + data.Delta + n;
            string Radius = "Radius: " + data.Radius + n;

            string Tap = "Tap: " + data.Tap + n;
            string StartPosition = "Start Position: " + data.StartPosition + n;
            string StartTime = "Start Time: " + data.StartTime + n;

            string Scroll = "Scroll: " + data.Scroll + n;

            inputText.text = Time.time + n + Press + PressCount + Position + Delta + Radius + n + Tap + StartPosition + StartTime + n + Scroll;

        }

        public void OnButtonPress() => buttonText.text = "Pressed at:\n" + Time.time;
    }

}


texts:
I changed the units in Blender so they are identical to Unity 3d. If I make a 1m^3 box in Blender, it will import into unity as exactly the same size as the standard cube.

With 3ds max, I changed the unit setup to metric and made sure it was centimeters in the system unit setup tab. However, when I import an obj file made in Blender and used in Unity, it is absolutely tiny. I have to convert the model to meters on import and then, when exporting, I have to set the model scale to .01 otherwise it is enormous in the unity scene.

I've tried changing the max units to meters and nothing changed.

How do you change the max unit/grid setup so one grid unit is 1m^2 and exactly equivalent to unity's grid?


texts:
I am making a real time strategy game in XNA. I have separated the Client (rendering, input, sound) code from the Sim (game logic).

I want to have features like replaying and fast forwarding. Also, I would like to give the Sim longer time intervals in its Update to finish its work without having to always implement time slicing to prevent frame rate stuttering.
I imagine I can do this when the two systems become decoupled and have their own update frequency.

So, how can I run the Client and Sim at two different update intervals? How should I code it?

Currently I am running with FixedTimeStep = false and using ElapsedGameTime in Update() computations. Can I create new GameTime instances to leverage this existing code..?


texts: How can I tell the player that a key or other item can be discarded?

texts:
We're working on a survival horror classical Resident evil (1, 2, 3, 0, REmake) type of game - link.

I'm using Unity3D with C#.

There's something that's kinda puzzling me - more a game design question than a technical one.

Item usage - In Resident Evil - You could use a key to open more than one door - when it's not needed anymore you'd get a "XXX key is not deeded anymore, discard?" YES|NO. I was curious as to how would one implement this in an elegant manner...

First, we should discuss who knows about the other, is it the key
that knows what doors it opens? or is it the door that knows which
key fits in its keyhole? - Well, it's kinda both if you think about
it. For example, a diamond shaped key, opens doors with diamond
shaped keyholes - Looking at the key you know which doors it could
open - Same said about the door - you look at it and know what type
of key you need...
If we went with the first approach in that a key knows what doors
it unlocks, we should have to assign those doors to the key - handle
them to it in some way - What if you had a key, that will remain
with you for a very long period - let's say it opens so many doors
that some of those doors are in the middle of the game - Why would a
key you pickup in the beginning of the game, carry information about
something that would occur in the middle of the game? Seems redudant
to me... So I wouldn't go with this approach.
OK, so you tell doors which key fits in them - Get in a scene
with 3 doors, information about what keys to use for those 3 doors
are loaded, and nothing else! - So I guess, we got that out of the
way...
Now, how would you tell, that a key is not needed anymore? I
thought of two approaches - both have downsides:

Have a nUsages counter - that you preset (via inspector for ex) - This way you have to know exactly how many times it will be used in the game - Add another door and forget to increment the counter, you get screwed. Each time you open a door/use the key, you decrement the counter by one, reach zero -> "You don't need this key anymore, discard>" YES|NO.
Detect the doors a key gets used in dynamically (When you pick up the key?) - So maybe you'd have like a database of DoorTriggers - Pickup key -> Look up the key's entries and increment the counter that way - This is slow relatively to the previous method. It's also kinda foggy a bit - You know, a key could open doors in scenes other than the one it's picked in - how would I go about searching for its doors in this case? (Getting a bit Unity3D-specific here...) - I guess, to answer this we must answer: How do doors register themselves in our db? Upon scene load? If that's the case, then a key picked up a scene A - can't detect a door it opens in Scene B where B > A...

Note that a key is just an example - There are Usable items that I don't need to do this - Like health items - The items that I must perform this operation on, are "Other" items, like keys, a crank, a wrench, a pipe, a holeopener, etc.

Again, this is what's off the surface of my head.

What do you think of my assessment? How would you implement this feature? (maybe in a better way?) (General ideas)

And if you'd go with my 2nd method in adding the stuff dynamically upon item pickup, how would you do it in Unity3D - More accurately, how would you look up the key's doors that resides in other scenes? and how where would you let the doors register themselves in teh db? (General approaches again)

Thanks for any help.

EDIT: UA Crosslink.


texts: How can i display some text information in the middle of the screen in a box?

texts:
Something nice to display text.

What i did so far: When the player is pointing with the camera on "Interactable" object it's showing on the object a description text. Then when the player is making left mouse click it will display more information about the object.

The problem is that it's showing the clicked text under the already exist text and not in the middle of the screen in a nice box.

This script is attached to the Player. I'm using two bool variables to check when to display the information: hasDescription and clickForDescription.

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

public class DetectInteractable : MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public Image image;
    public bool interactableObject = false;
    public Canvas canvas;
    public Text interactableText;
    public ItemInformation iteminformation;

    private RaycastHit whatObjectHit;
    private RotateObject rotateobj;
    private bool hasDescription = false;
    private bool clickForDescription = false;
    private int layerMask = 1 << 8;

    private void Start()
    {
        rotateobj = GetComponent<RotateObject>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickForDescription = true;
        }

        Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);

        if (rotateobj.rotating == false)
        {
            if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask))
            {
                image.color = Color.red;
                objectHit = whatObjectHit.collider.gameObject.name;
                interactableObject = true;
                interactableText.gameObject.SetActive(true);
                interactableText.text = whatObjectHit.collider.gameObject.name;
                print("Hit ! " + whatObjectHit.collider.gameObject.name);
                hasDescription = true;
            }
            else
            {
                image.color = Color.white;
                interactableText.gameObject.SetActive(false);
                hasDescription = false;
                clickForDescription = false;
                print("Not Hit !");
            }
        }
    }

    private void OnGUI()
    {
        if (hasDescription == true && clickForDescription == true)
        {
            var centeredStyle = GUI.skin.GetStyle("Label");
            centeredStyle.alignment = TextAnchor.UpperCenter;
            GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle);
        }
    }

    public class ViewableObject : MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}

The second script is attached to each "Interactable" gameobject and i'm writing for each object some information. This is the text i want to display in the middle of the screen or in some position on the screen to display mroe information about the item/object.

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

public class ItemInformation : MonoBehaviour
{
    [TextArea]
    public string description;
}

In this screenshot it's when i'm pointing with the camera on "Interactable" object the pointer is turning red and the text description is in white. This is fine and working good:

And this is when pointing on "Interactable" object and then clicking on the mouse left button: What i want is to display the new text information in a nice big box in the middle of the screen with some bigger size of the fonts like in adventure games when you click on item and it's giving you description.

The first white short description should be stay on the object/item the text in ItmeInformation script should be in the middle of the screen like in adventure/quest games.


texts: Problem with position for player and 2D camera

texts:
I'm not sure I understand how the Matrix class for a 2D camera works in XNA. I have a Player object that I'm trying to position in the middle of the screen and then I have the Camera object that I want to follow the Player. But The position of the player is at the top left corner!?

Preciate som help to understand and to improve my code.

Game1.cs

player = new Player(texturePlayer, new Vector2(screenSizeX / 2, screenSizeY / 2));

And in the Update method:

camera.Position = player.PlayerPosition;

The Camera class:

    class Camera
{
    public Vector2 Position { get; set; }
    private Viewport viewPort;

    // Konstruktor
    public Camera(Viewport viewPort)
    {
        this.viewPort = viewPort;
        Position = Vector2.Zero;
    }
    public Matrix GetViewPortMatrix()
    {
        return Matrix.CreateTranslation(new Vector3(-Position, 0f));
    }
}

I guess there is no need to calcualte an origin for the Matrix when the camera isn't going to rotate!?

And finally some part of the Player class. Note that I'm using a "timer" to achieve a movement of the player in steps. Is this OK or is there a better way to achieve this?

    class Player:GameObjects
{
    //public Vector2 Position { get { return position; } }

    private int walkingSpeed = 60;
    private float walkingTimer = 100;
    private float milliSeconds1;

    // Konstruktor
    public Player(Texture2D texture, Vector2 position) : base(texture, position)
    {
    }

    public void Update(GameTime gameTime)
    {
        milliSeconds1 += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
    }

    public Vector2 PlayerPosition
    {
        get
        {
            return position;
        }
        set
        {
            position = value;
        }
    }

    public void Up()
    {
        if (milliSeconds1 >= walkingTimer)
        {
            if(position.Y > 60)
                position.Y -= walkingSpeed;

            milliSeconds1 = 0;
        }
    }

    public void Down()
    {
        if (milliSeconds1 >= walkingTimer)
        {
            if(position.Y < 630)
                position.Y += walkingSpeed;

            milliSeconds1 = 0;
        }
    }


texts: Should I call the garbage collector during loading screen?

texts:
SO, I read a bit on Garbage Collection lately, out of curiosity, and there is something that is repeated quite often: garbage collection can lead to sudden slow down of the program, depending of the "depth" of the collection.

But in video games, there is a moment where the user can't really notice a small lag: loading screen. So, I thought, it might be useful to proceed to full garbage collection during a loading phase (via Collect()), having to wait a second or two longer should not really impact the user.

My question is, is it really useful, or are there no real benefit to doing this?


texts: Rendering issue: depth buffering + blending: how do they work together?

texts:
This image describes the problem I'm having:

What you are seeing consists of two images:

Image A(with the alien-concept art thingy), depth value .98, the white parts on the image is where the alpha value is 0.0f
Image B(with the play game button thingy), depth value .99, one solid image without any transparency value.

Now, when I first set this up, I expected Image A to let the colours of Image B through where Image A is fully transparent. But it doesn't

Question 1 : Why doesn't it?

Question 2 : What can I do to fix it? Are there multiple ways to fix it?

Question 3 : Is this problem different for partial transparency? If so, how do I make it work with partial transparency as well?

Thanks.


texts: Help with understanding "transform.root.GetComponent" in Unity

texts:
I'm reading through a tutorial for making an RTS in Unity, and in certain scripts it wants you to make a Player field and then OnStart(){ transform.root.GetComponent}. I am not quite getting what that does or what purpose it serves.

Player.cs is added as a component to the game object "Player". Player.cs is the following:

public class Player : MonoBehaviour {

public string username { get; set; }
public bool human { get; set; }
}

Then on another script which is also attached to the Player (gameobject) as a component:

protected Player player;

protected void Start ()
{
    player = transform.root.GetComponent<Player>();
}

This is instructed: http://stormtek.geek.nz/rts_tutorial/part2.php right under "Camera Input". There is a description there, but I am confused by it since it does not allow you to actually interact with the game object Player, but the instance of the Player script.

I'm sorry if this was poorly worded, I can't think of a better way to ask this question. I am completely confused as to why it asks you to do this and what it actually does. I'm also very confused about how to reference instances of a class that are attached to a game object, and if the snippet in question assists with that (I can remove the snippet and things seem to work fine).

Edit: I have looked at the unity documentation on game objects, transform, root, getcomponents and other related methods.


texts: Implementing Galaga Style Enemy Behavior in Unity

texts:
I've been trying to work on a space shooter with the idea of having enemies behaving like it is shown in this video : https://www.youtube.com/watch?v=3p7u8uCR6yw

In the video above, enemies fly from different portions outside the view area of the screen doing elaborate movement before finding a spot to form an organized formation.

I've been thinking of ways how this could all be done. One way is by having either the enemies and/or a manager use a Finite State Machine that will control when there is a "performing" state and when there is a "FindingSpot" state.

but at as far as implementing the complex patterns, I'm at a loss. Is there some sort of Math formulation that's used to generate those movement patterns?


texts: Order of render with transparency opengl

texts:
I tried to render using different render configurations (GL_BLEND_FUNC()) but I couldn't get the back object to render in certain angles. The first screenshot here shows one angle where the back object is not visible through the front one. In th second screenshot, I looked at the blocks from 180 degrees.

Is there a way I could render them through? Or would I have to implement a sorting algorithm?


texts:
I've been working on a program for my friends to use for a homebrewed roleplay system that we all use for our campaigns that can generate random enemy statlines with certain constraints.

The program accepts a list of the statlines of the players, and then the user inputs a number that denotes a percentage of the player characters that this unit can beat on average in a 1v1. The issue I'm struggling with here is that combat involves different formulas for determining hit rate, critical hit rate, and damage

The formulas I have to deal with are:

Physical damage: strength - enemy defense = damage (multiplied by 2 if user's speed is 5 greater than enemy's)

Magical damage: magic - enemy resistance = damage (multiplied by 2 if user's speed is 5 greater than enemy's)

Hit rate: base hit + floor(user dex/3) + floor(user luck/5) - enemy dodge rate = hit rate (will always have a minimum of 5%)

Dodge rate: base dodge + floor(user speed/4) * 2 + floor(user luck/5) = dodge

Critical hit rate: 5% + floor((user dex - enemy luck)/5) + crit bonus = critical hit rate

(hit system is based on singular d20 with critical hit rate equivalent to number range on d20 that's considered a critical hit, meaning a 5% hit chance with a 5% or greater critical hit rate will result in every hit being a critical hit)

I've been struggling to think of an algorithm that can generate enemy statlines based on these formulas as well as the percentage constraint but I have no idea how to go about it in a way that isn't just bruteforcing it until I get a desirable outcome. I've toyed around with ideas such as ranking the inputting players based on their damage, survivability, dodge/hit, and determining upper/lower bounds on stats to work with but the issue I have is trying to establish a relationship formula between each stat to make sure that when I tweak one stat, I can change the others accordingly while staying within the user-defined constraints.

EDIT: After some thinking, I did come up with one possible solution, that being first determining the upper and lower bounds for the statline based on player stats, generating a random statline in between those bounds, and then generating tables that determine what effect on player and enemy DPS incrementing/decrementing a stat will have, and using that to precisely tweak enemies. The only issue with this solution is that for very high/diverse player stat values, this can take a long time, as well as figuring out a way to determine which stat to increment/decrement in the algorithm.


texts: How can i make all the scene dark/night and spot a light on specific place/area in the scene?

texts:
I want to light the area of the 5 spheres. All the rest to be dark.
What i have in the Hierarchy is Directional Light.
I'm not sure if i need other lights objects and what to do to make it dark/night environment and how to spot a light on the specific area.


texts: Best strategy to track object hierarchy using groups and obj files

texts:
I am making a 3D game in OpenGL from scratch. In this game I have a ship with stuff inside it. How can I attach the stuff to the ship in the CAD program and maintain that hierarchy in my own game?

For example say I have a fire extinguisher in my ship that mounts on the wall.  There are two approaches both with problems.

Solution 1: Save fire extinguisher and ship as separate obj files.

Problem: How can I place the fire extinguisher in the proper place inside my ship in my game?  With hundreds of objects manually placing them is completely infeasible. I want to arrange stuff in my CAD and load it into the game and be done.

Solution 2: Save fire extinguisher as its own group inside the ship obj file.

Problem: Now I can't reuse the fire extinguisher in other ships. The obj files for game assets will balloon out of control in size with new instances of reused sub-objects.

Is there some way I can specify the position of an external object? A 3d point in my ship obj file representing the origin of another obj model?


texts: Why do my obstacles float above the ground? Unity2D

texts:
I'm making an infinite runner game and I'm trying to spawn obstacles, but all of them float far above the ground instead of being at the ground level.

This is the code on summoning the bears.

  PlatformGenerator Class

    if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (0f, 0f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);
        }

Ask me more about the game if you need more information.

Edit:

Here is the whole class.

  The PlatformGenerator Class

using UnityEngine;
using System.Collections;

public class PlatformGenerator : MonoBehaviour {

public GameObject thePlatform;
public Transform generationPoint;
public float distanceBetween;

private float platformWidth;

public ObjectPooler theObjectPool;

public float randomEnemyThreshold;
public ObjectPooler enemyPool;

// Käytä alkuarvon alustamiseen
void Start () {
    platformWidth = thePlatform.GetComponent<BoxCollider2D>().size.x;

}

// Päivitys tulee joka ruutu
void Update () {

    if (transform.position.x < generationPoint.position.x)
    {
        transform.position = new Vector3 (transform.position.x + platformWidth + distanceBetween, transform.position.y, transform.position.z);

        //Instantiate (thePlatform, transform.position, transform.rotation);
        GameObject newPlatform = theObjectPool.GetPooledObject();

        newPlatform.transform.position = transform.position;
        newPlatform.transform.rotation = transform.rotation;
        newPlatform.SetActive (true);

        if (Random.Range (0f, 100f) < randomEnemyThreshold)
        {
            GameObject newEnemy = enemyPool.GetPooledObject();

            Vector3 enemyPosition = new Vector3 (0f, 0.5f, 0f);

            newEnemy.transform.position = transform.position + enemyPosition;
            newEnemy.transform.rotation = transform.rotation;
            newEnemy.SetActive(true);
        }
    }

}

}


texts: How to set a box2d body to follow a strict path

texts:
I'm making an infinite runner type game and I want one of my enemies (when it's created) to swoop down in a sort of U motion where it'll hit the player if they don't react quick enough once the enemy (bat) leaves the screen it'll be destroyed and created again once certain requirements are met . The path will be the same each time so I don't need anything to do with AI. Unfortunately I'm only in grade 10 so calculus makes no sense to me and neither does the pathfinding libgdx documentation. I either need something similar to this (But written for libgdx) or some way to get a box2d body to move in an exact way.

My game is structured like this:

in Bat.java:

public class Bat extends Sprite {

private World world;

public Bat(GameScreen screen) {

    this.world = screen.getWorld();
}

In GameScreen.Java

public class GameScreen implements Screen {

private Bat bat = new Bat(this);

public World getWorld(){
    return world;
}


texts: How can I handle versioning changes when saving assets?

texts:
I've been working on an RPG now for a while and I use two of different serialization techniques.

Enemies, Weapons, items are as saved as XML.
Maps and events are saved as "controlled binary" (every class get a save/load method and they decide what they want to save/load).

But I have started to question my choice for maps and events. My concerns:

I have created a map editor but I still miss being able to change small things by just opening the file.
Changes mess so much up. Say that I want to add a variable to a class, if I don't load/save every map again it break later.

The first concern is hard to get around without changing my technique. I thought about changing to JSON, but it's a lot of work. I also think it look pretty ugly with [DataContract] and [DataMember] attributes everywhere.

That leave me with my second concern and I wonder how I can deal with it? Do you create a small program that loop through all maps and re-save them with the new variable? Because I start to get a couple of maps now and I still do it manually. It make me think twice everytime I want to do some changes as it create a lot of extra work.


texts: How can I calculate current level from total XP, when each level requires proportionally more XP?

texts:
In my game, XP needed to reach the next level is Current Level × Level Threshold.  Given that, how can I get my current level from the total XP ever earned?

For example:

Level Threshold = 50
Current Level = 1

Starting at level 1, I would need (1 × 50) = 50 XP to get to level 2, and so on.

Level 1: 50 XP needed to reach level 2
Level 2: 100 more XP needed to reach level 3
Level 3: 150 more XP needed to reach level 4

In other words, the progression table is as follows:

Level 1: 0 XP to 49 XP
Level 2: 50 XP to 149 XP
Level 3: 150 XP to 299 XP
Level 4: 300 XP to 499 XP

If I have 300 XP, I'll just reached level 4. How can I calculate that generally?


texts: Is there a rule of thumb to scale up the environment by 33%?

texts:
I was reading an article on Gamasutra called A Rational Approach to Racing Game Track Design, and I found the following:

  A commonly acknowledged rule for third person games is
  that the environment should be scaled up by a factor of
  around 33 percent (on page 2)

I am just curious: has anyone else heard of such a rule, and if so, where else could I find references to it?