Search Results

Search found 150 results on 6 pages for 'gameobject'.

Page 3/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Keep cube spinning after fling

    - by Zero
    So I've been trying to get started with game development for Android using Unity3D. For my first project I've made a simple cube that you can spin using touch. For that I have the following code: using UnityEngine; using System.Collections; public class TouchScript : MonoBehaviour { float speed = 0.4f; bool canRotate = false; Transform cachedTransform; public bool CanRotate { get { return canRotate; } private set { canRotate = value; } } void Start () { // Make reference to transform cachedTransform = transform; } // Update is called once per frame void Update () { if (Input.touchCount > 0) { Touch touch = Input.GetTouch (0); // Switch through touch events switch (Input.GetTouch (0).phase) { case TouchPhase.Began: if (VerifyTouch (touch)) CanRotate = true; break; case TouchPhase.Moved: if (CanRotate) RotateObject (touch); break; case TouchPhase.Ended: CanRotate = false; break; } } } bool VerifyTouch (Touch touch) { Ray ray = Camera.main.ScreenPointToRay (touch.position); RaycastHit hit; // Check if there is a collider attached already, otherwise add one on the fly if (collider == null) gameObject.AddComponent (typeof(BoxCollider)); if (Physics.Raycast (ray, out hit)) { if (hit.collider.gameObject == this.gameObject) return true; } return false; } void RotateObject (Touch touch) { cachedTransform.Rotate (new Vector3 (touch.deltaPosition.y, -touch.deltaPosition.x, 0) * speed, Space.World); } } The above code works fine. However, I'm wondering how I can keep the cube spinning after the user lifts his finger. The user should be able to "fling" the cube, which would keep spinning and after a while would slowly come to a stop due to drag. Should I do this using AddForce or something? I'm really new to this stuff so I'd like it if you guys could point me in the right direction here :) .

    Read the article

  • Correct way to use Farseer Physics in XNA

    - by user1640602
    I am using Farseer Physics for my 2D sidescroller game and I'm not sure how to proceed with it. I currently have a Sprite class (handles nothing but graphics), a GameObject class (contains specific object info like hit points), a World object which contains the list of Bodies, and a Level object which contains all of these objects. Originally I was trying to keep track of the Sprites, GameObjects, and Bodies separately because I felt that would provide loose coupling but it quickly became a headache. So my new idea was to add a Sprite member to the GameObject class but I'm still not sure how to maintain the Bodies because they have to communicate with GameObject. Specifically, my issue is this: The position of the Body is used to draw the Sprite inside of the Level. In order to do that I would have to maintain a link between GameObjects and Bodies. Is this correct or is there a better way to architect my game? If any of this is unclear please ask and I'll try to clarify. Thank you in advance for any help.

    Read the article

  • XNA - Inconsistent accessibility: parameter type is less accessible than method

    - by DijkeMark
    I have a level class in which I make a new turret. I give the turret the level class as parameter. So far so good. Then in the Update function of the Turret I call a function Shoot(), which has that level parameter it got at the moment I created it. But from that moment it gives the following error: Inconsistent accessibility: parameter type 'Space_Game.Level' is less accessible than method 'Space_Game.GameObject.Shoot(Space_Game.Level, string)' All I know it has something to do with not thr right protection level or something like that. The level class: public Level(Game game, Viewport viewport) { _game = game; _viewport = viewport; _turret = new Turret(_game, "blue", this); _turret.SetPosition((_viewport.Width / 2).ToString(), (_viewport.Height / 2).ToString()); } The Turret Class: public Turret(Game game, String team, Level level) :base(game) { _team = team; _level = level; switch (_team) { case "blue": _texture = LoadResources._blue_turret.Texture; _rows = LoadResources._blue_turret.Rows; _columns = LoadResources._blue_turret.Columns; _maxFrameCounter = 10; break; default: break; } _frameCounter = 0; _currentFrame = 0; _currentFrameMultiplier = 1; } public override void Update() { base.Update(); SetRotation(); Shoot(_level, "turret"); } The Shoot Function (Which is in GameObject class. The Turret Class inherited the GameObject Class. (Am I saying that right?)): protected void Shoot(Level level, String type) { MouseState mouse = Mouse.GetState(); if (mouse.LeftButton == ButtonState.Pressed) { switch (_team) { case "blue": switch (type) { case "turret": TurretBullet _turretBullet = new TurretBullet(_game, _team); level.AddProjectile(_turretBullet); break; default: break; } break; default: break; } } } Thanks in Advance, Mark Dijkema

    Read the article

  • Undefined fireball movement behavior

    - by optimisez
    Demonstration video I try to do after the player shoot 10 times of fireball, then delete all the fireball objects and recreate a 10 new set of fireball objects. I did it but there is a weird bug happens that sometimes the fireball will come out from top and move to the right after shooting a few times. All the 10 fireballs should follow the player all the time and all the fireball should come out from player even after a new set of fireballs is recreated. Any ideas to fix it? Variables typedef struct gameObject{ float X; float Y; int length; int height; bool action; }; // Fireball #define FIREBALL_NUM 10 LPDIRECT3DTEXTURE9 fireball = NULL; RECT fireballRect; gameObject *fireballDest = new gameObject[FIREBALL_NUM]; int iFireBallAnimation; int fireballCount = 0; Set up Fireball void setUpFireBall() { // Initialize destination rectangle, rectangle height and length for (int i = 0; i < FIREBALL_NUM; i++) { fireballDest[i].X = 0; fireballDest[i].Y = 0; fireballDest[i].length = fireballRect.right - fireballRect.left; fireballDest[i].height = fireballRect.bottom - fireballRect.top; } iFireBallAnimation = fireballRect.right - fireballRect.left; // Initialize boolean for (int i = 0; i < FIREBALL_NUM; i++) { fireballDest[i].action = false; } } Initialize fireball void initFireball() { hr = D3DXCreateTextureFromFileEx(d3dDevice, "fireball.png", 512, 512, D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 0), NULL, NULL, &fireball); // Initialize source rectangle fireballRect.left = 0; fireballRect.top = 256; fireballRect.right = 64; fireballRect.bottom = 320; setUpFireBall(); } Update fireball void update() { updateAnimation(); updateAI(); updatePhysics(); updateGameState(); } void updatePhysics() { motion(); collison(); } void motion() { playerMove(); playerJump(); playerGravity(); shootFireball(); fireballFollowPlayer(); } void shootFireball() { if (keyArr['Z']) fireballDest[fireballCount].action = true; if (fireballDest[fireballCount].action) { fireballDest[fireballCount].X += 10; if (fireballDest[fireballCount].X > 800) fireballCount++; } } void fireballFollowPlayer() { for (int i = 0; i < FIREBALL_NUM; i++) { if (fireballDest[i].action == false) { fireballDest[i].X = playerDest.X - 30; fireballDest[i].Y = playerDest.Y - 14; } } } void updateGameState() { // When no more fireball left, rearm fireball if (fireballCount == FIREBALL_NUM) { delete[] fireballDest; fireballDest = new gameObject[10]; fireballCount = 0; setUpFireBall(); } } Render fireball void renderFireball() { for (int i = 0; i < FIREBALL_NUM; i++) { if (fireballDest[i].action) sprite->Draw(fireball, &fireballRect, NULL, &D3DXVECTOR3(fireballDest[i].X, fireballDest[i].Y, 0), D3DCOLOR_XRGB(255,255, 255)); } }

    Read the article

  • Stack overflow error after creating a instance using 'new'

    - by Justin
    EDIT - The code looks strange here, so I suggest viewing the files directly in the link given. While working on my engine, I came across a issue that I'm unable to resolve. Hoping to fix this without any heavy modification, the code is below. void Block::DoCollision(GameObject* obj){ obj->DoCollision(this); } That is where the stack overflow occurs. This application works perfectly fine until I create two instances of the class using the new keyword. If I only had 1 instance of the class, it worked fine. Block* a = new Block(0, 0, 0, 5); AddGameObject(a); a = new Block(30, 0, 0, 5); AddGameObject(a); Those parameters are just x,y,z and size. The code is checked before hand. Only a object with a matching Collisonflag and collision type will trigger the DoCollision(); function. ((*list1)->m_collisionFlag & (*list2)->m_type) Maybe my check is messed up though. I attached the files concerned here http://celestialcoding.com/index.php?topic=1465.msg9913;topicseen#new. You can download them without having to sign up. The main suspects, I also pasted the code for below. From GameManager.cpp void GameManager::Update(float dt){ GameList::iterator list1; for(list1=m_gameObjectList.begin(); list1 != m_gameObjectList.end(); ++list1){ GameObject* temp = *list1; // Update logic and positions if((*list1)->m_active){ (*list1)->Update(dt); // Clip((*list1)->m_position); // Modify for bounce affect } else continue; // Check for collisions if((*list1)->m_collisionFlag != GameObject::TYPE_NONE){ GameList::iterator list2; for(list2=m_gameObjectList.begin(); list2 != m_gameObjectList.end(); ++list2){ if(!(*list2)->m_active) continue; if(list1 == list2) continue; if( (*list2)->m_active && ((*list1)->m_collisionFlag & (*list2)->m_type) && (*list1)->IsColliding(*list2)){ (*list1)->DoCollision((*list2)); } } } if(list1==m_gameObjectList.end()) break; } GameList::iterator end    = m_gameObjectList.end(); GameList::iterator newEnd = remove_if(m_gameObjectList.begin(),m_gameObjectList.end(),RemoveNotActive); if(newEnd != end)        m_gameObjectList.erase(newEnd,end); } void GameManager::LoadAllFiles(){ LoadSkin(m_gameTextureList, "Models/Skybox/Images/Top.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Models/Skybox/Images/Right.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Models/Skybox/Images/Back.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Models/Skybox/Images/Left.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Models/Skybox/Images/Front.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Models/Skybox/Images/Bottom.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Terrain/Textures/Terrain1.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Terrain/Textures/Terrain2.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Terrain/Details/TerrainDetails.bmp", GetNextFreeID()); LoadSkin(m_gameTextureList, "Terrain/Textures/Water1.bmp", GetNextFreeID()); Block* a = new Block(0, 0, 0, 5); AddGameObject(a); a = new Block(30, 0, 0, 5); AddGameObject(a); Player* d = new Player(0, 100,0); AddGameObject(d); } void Block::Draw(){ glPushMatrix(); glTranslatef(m_position.x(), m_position.y(), m_position.z()); glRotatef(m_facingAngle, 0, 1, 0); glScalef(m_size, m_size, m_size); glBegin(GL_LINES); glColor3f(255, 255, 255); glVertex3f(m_boundingRect.left, m_boundingRect.top, m_position.z()); glVertex3f(m_boundingRect.right, m_boundingRect.top, m_position.z()); glVertex3f(m_boundingRect.left, m_boundingRect.bottom, m_position.z()); glVertex3f(m_boundingRect.right, m_boundingRect.bottom, m_position.z()); glVertex3f(m_boundingRect.left, m_boundingRect.top, m_position.z()); glVertex3f(m_boundingRect.left, m_boundingRect.bottom, m_position.z()); glVertex3f(m_boundingRect.right, m_boundingRect.top, m_position.z()); glVertex3f(m_boundingRect.right, m_boundingRect.bottom, m_position.z()); glEnd(); // DrawBox(m_position.x(), m_position.y(), m_position.z(), m_size, m_size, m_size, 8); glPopMatrix(); } void Block::DoCollision(GameObject* obj){ GameObject* t = this;   // I modified this to see for sure that it was causing the mistake. // obj->DoCollision(NULL); // Just revert it back to /* void Block::DoCollision(GameObject* obj){     obj->DoCollision(this);   }   */ }

    Read the article

  • How does one refer to the game1 class's variables in XNA

    - by user1149068
    I try to refer to an array in the Game1 class by creating an object of the Game1 class with its definition Game1 gameObject; , its declaration gameObject = new Game1(); in the constructor, and its usage gameObject.tileArray[xInt, yInt].treed = true;. The game1 class itself remains unchanged in its class code other than some methods and variables. When I try to use this code in the TreeRegion class it gives me "Object reference not set to an instance of an object," leading me to believe that the game1 class is null somehow. How might one change the class or object in order to refer to game1's variables? Mind you I am self-taught and still rather new to C#. The class that refers to game1: http://pastebin.com/0chEcKfq Game1 itself http://pastebin.com/zLDVzCca

    Read the article

  • Unity 2D Instantiating a prefab with it's components

    - by TazmanNZL
    I have some block prefabs that I add to an array of game objects: public GameObject[]blocks; Each prefab has a BoxCollider2D, Script & Rigidbody2D components. But when I try to instantiate the prefab in the scene it doesn't appear to have the components attached? Here is how I am instantiating the prefab: for (int i = 0; i < 4; i++) { for (int j = 0; j < gridWidth; j++) { blockClone = Instantiate (blocks [Random.Range (0, blocks.Length)] as GameObject, new Vector3 (j, -i-2, 0f), transform.rotation) as GameObject; } } What am I doing wrong?

    Read the article

  • Sphere entering in to the cube.unity

    - by Parthi
    I am trying Roll a Ball unity tutorial.Everything is fine,but when I roll the ball it is moving through the cube instead of picking it. my player class is using UnityEngine; using System.Collections; public class player : MonoBehaviour { public float speed; // Use this for initialization // Update is called once per frame void Update () { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 move = new Vector3(h,0,v); rigidbody.AddForce(move * speed * Time.deltaTime); } void OnTriggerEnter(Collider other) { if(other.gameObject.tag == "Pick up") { other.gameObject.SetActive(false); } } }

    Read the article

  • Unity: how to apply programmatical changes to the Terrain SplatPrototype?

    - by Shivan Dragon
    I have a script to which I add a Terrain object (I drag and drop the terrain in the public Terrain field). The Terrain is already setup in Unity to have 2 PaintTextures: 1 is a Square (set up with a tile size so that it forms a checkered pattern) and the 2nd one is a grass image: Also the Target Strength of the first PaintTexture is lowered so that the checkered pattern also reveals some of the grass underneath. Now I want, at run time, to change the Tile Size of the first PaintTexture, i.e. have more or less checkers depending on various run time conditions. I've looked through Unity's documentation and I've seen you have the Terrain.terrainData.SplatPrototype array which allows you to change this. Also there's a RefreshPrototypes() method on the terrainData object and a Flush() method on the Terrain object. So I made a script like this: public class AStarTerrain : MonoBehaviour { public int aStarCellColumns, aStarCellRows; public GameObject aStarCellHighlightPrefab; public GameObject aStarPathMarkerPrefab; public GameObject utilityRobotPrefab; public Terrain aStarTerrain; void Start () { //I've also tried NOT drag and dropping the Terrain on the public field //and instead just using the commented line below, but I get the same results //aStarTerrain = this.GetComponents<Terrain>()[0]; Debug.Log ("Got terrain "+aStarTerrain.name); SplatPrototype[] splatPrototypes = aStarTerrain.terrainData.splatPrototypes; Debug.Log("Terrain has "+splatPrototypes.Length+" splat prototypes"); SplatPrototype aStarCellSplat = splatPrototypes[0]; Debug.Log("Re-tyling splat prototype "+aStarCellSplat.texture.name); aStarCellSplat.tileSize = new Vector2(2000,2000); Debug.Log("Tyling is now "+aStarCellSplat.tileSize.x+"/"+aStarCellSplat.tileSize.y); aStarTerrain.terrainData.RefreshPrototypes(); aStarTerrain.Flush(); } //... Problem is, nothing gets changed, the checker map is not re-tiled. The console outputs correctly tell me that I've got the Terrain object with the right name, that it has the right number of splat prototypes and that I'm modifying the tileSize on the SplatPrototype object corresponding to the right texture. It also tells me the value has changed. But nothing gets updated in the actual graphical view. So please, what am I missing?

    Read the article

  • How to apply programatical changes to the Terrain SplatPrototype

    - by Shivan Dragon
    I have a script to which I add a Terrain object (I drag and drop the terrain in the public Terrain field). The Terrain is already setup in Unity to have 2 PaintTextures: 1 is a Square (set up with a tile size so that it forms a checkered pattern) and the 2nd one is a grass image: Also the Target Strength of the first PaintTexture is lowered so that the checkered pattern also reveals some of the grass underneath. Now I want, at run time, to change the Tile Size of the first PaintTexture, i.e. have more or less checkers depending on various run time conditions. I've looked through Unity's documentation and I've seen you have the Terrain.terrainData.SplatPrototype array which allows you to change this. Also there's a RefreshPrototypes() method on the terrainData object and a Flush() method on the Terrain object. So I made a script like this: public class AStarTerrain : MonoBehaviour { public int aStarCellColumns, aStarCellRows; public GameObject aStarCellHighlightPrefab; public GameObject aStarPathMarkerPrefab; public GameObject utilityRobotPrefab; public Terrain aStarTerrain; void Start () { //I've also tried NOT drag and dropping the Terrain on the public field //and instead just using the commented line below, but I get the same results //aStarTerrain = this.GetComponents<Terrain>()[0]; Debug.Log ("Got terrain "+aStarTerrain.name); SplatPrototype[] splatPrototypes = aStarTerrain.terrainData.splatPrototypes; Debug.Log("Terrain has "+splatPrototypes.Length+" splat prototypes"); SplatPrototype aStarCellSplat = splatPrototypes[0]; Debug.Log("Re-tyling splat prototype "+aStarCellSplat.texture.name); aStarCellSplat.tileSize = new Vector2(2000,2000); Debug.Log("Tyling is now "+aStarCellSplat.tileSize.x+"/"+aStarCellSplat.tileSize.y); aStarTerrain.terrainData.RefreshPrototypes(); aStarTerrain.Flush(); } //... Problem is, nothing gets changed, the checker map is not re-tiled. The console outputs correctly tell me that I've got the Terrain object with the right name, that it has the right number of splat prototypes and that I'm modifying the tileSize on the SplatPrototype object corresponding to the right texture. It also tells me the value has changed. But nothing gets updated in the actual graphical view. So please, what am I missing?

    Read the article

  • Unity DontDestroyOnLoad causing scenes to stay open

    - by jkrebsbach
    Originally posted on: http://geekswithblogs.net/jkrebsbach/archive/2014/08/11/unity-dontdestroyonload-causing-scenes-to-stay-open.aspxMy Unity project has a class (ClientSettings) where most of the game state & management properties are stored.  Among these are some utility functions that derive from MonoBehavior.  However, between every scene this object was getting recreated and I was losing all sorts of useful data.  I learned that with DontDestroyOnLoad, I can persist this entity between scenes.  Super.Persisting information between scenesThe problem with adding DontDestroyOnLoad to my "ClientSettings" was suddenly my previous scene would stay alive, and continue to execute its update routines.  An important part of the documentation helps shed light to my issues:"If the object is a component or game object then its entire transform hierarchy will not be destroyed either."My ClientSettings script was attached to the main camera on my first scene.  Because of this, the Main Camera was part of the hierarchy of the component, and therefore was also not able to destroy when switching scenes.  Now the first scene's main camera Update routine continues to execute after the second scene is running - causing me to have some very nasty bugs.Suddenly I wasn't sure how I should be creating a persistent entity - so I created a new sandbox project and tested different approaches until I found one that works:In the main scene: Create an empty Game Object:  "GameManager" - and attach the ClientSettings script to this game object.  Set any properties to the clientsettings script as appropriate.Create a prefab, using the GameManager.Remove the Game Object from the main scene.In the Main Camera, I created a script:  Main Script.  This is my primary script for the main scene.<code> public GameObject[] prefabs; private ClientSettings _clientSettings; // Use this for initialization void Start () { GameObject res = (GameObject)Instantiate(prefabs[0]); }</code>Now go back out to scene view, and add the new GameManager prefab to the prefabs collection of MainScript.When the main scene loads, the GameManager is set up, but is not part of the main scene's hierarchy, so the two are no longer tied up together.Now in our second scene, we have a script - SecondScript - and we can get a reference to the ClientSettings we created in the previous scene like so:<code>private ConnectionSettings _clientSettings; // Use this for initialization void Start () { _clientSettings = FindObjectOfType<ConnectionSettings> (); }</code>And the scenes can start and finish without creating strange long-running scene side effects.

    Read the article

  • "Optimal" game loop for 2D side-scroller

    - by MrDatabase
    Is it possible to describe an "optimal" (in terms of performance) layout for a 2D side-scroller's game loop? In this context the "game loop" takes user input, updates the states of game objects and draws the game objects. For example having a GameObject base class with a deep inheritance hierarchy could be good for maintenance... you can do something like the following: foreach(GameObject g in gameObjects) g.update(); However I think this approach can create performance issues. On the other hand all game objects' data and functions could be global. Which would be a maintenance headache but might be closer to an optimally performing game loop. Any thoughts? I'm interested in practical applications of near optimal game loop structure... even if I get a maintenance headache in exchange for great performance.

    Read the article

  • Physics/Graphics Components

    - by Brett Powell
    I have spent the last 48 hours reading up on Object Component systems, and feel I am ready enough to start implementing it. I got the base Object and Component classes created, but now that I need to start creating the actual components I am a bit confused. When I think of them in terms of HealthComponent or something that would basically just be a property, it makes perfect sense. When it is something more general as a Physics/Graphics component, I get a bit confused. My Object class looks like this so far (If you notice any changes I should make please let me know, still new to this)... typedef unsigned int ID; class GameObject { public: GameObject(ID id, Ogre::String name = ""); ~GameObject(); ID &getID(); Ogre::String &getName(); virtual void update() = 0; // Component Functions void addComponent(Component *component); void removeComponent(Ogre::String familyName); template<typename T> T* getComponent(Ogre::String familyName) { return dynamic_cast<T*>(m_components[familyName]); } protected: // Properties ID m_ID; Ogre::String m_Name; float m_flVelocity; Ogre::Vector3 m_vecPosition; // Components std::map<std::string,Component*> m_components; std::map<std::string,Component*>::iterator m_componentItr; }; Now the problem I am running into is what would the general population put into Components such as Physics/Graphics? For Ogre (my rendering engine) the visible Objects will consist of multiple Ogre::SceneNode (possibly multiple) to attach it to the scene, Ogre::Entity (possibly multiple) to show the visible meshes, and so on. Would it be best to just add multiple GraphicComponent's to the Object and let each GraphicComponent handle one SceneNode/Entity or is the idea to have one of each Component needed? For Physics I am even more confused. I suppose maybe creating a RigidBody and keeping track of mass/interia/etc. would make sense. But I am having trouble thinking of how to actually putting specifics into a Component. Once I get a couple of these "Required" components done, I think it will make a lot more sense. As of right now though I am still a bit stumped.

    Read the article

  • Another question about handling game states

    - by Eva
    I'm making a game designed with the entity-component paradigm that uses systems to communicate between components as explained here. I've reached the point in my development that I need to add game states (such as paused, playing, level start, round start, game over, etc.), but I'm not sure how to do it with my framework. I've looked at this code example on game states which everyone seems to reference, but I don't think it fits with my framework. It seems to have each state handling its own drawing and updating. My framework has a SystemManager that handles all the updating using systems. For example, here's my RenderingSystem class: public class RenderingSystem extends GameSystem { private GameView gameView_; /** * Constructor * Creates a new RenderingSystem. * @param gameManager The game manager. Used to get the game components. */ public RenderingSystem(GameManager gameManager) { super(gameManager); } /** * Method: registerGameView * Registers gameView into the RenderingSystem. * @param gameView The game view registered. */ public void registerGameView(GameView gameView) { gameView_ = gameView; } /** * Method: triggerRender * Adds a repaint call to the event queue for the dirty rectangle. */ public void triggerRender() { Rectangle dirtyRect = new Rectangle(); for (GameObject object : getRenderableObjects()) { GraphicsComponent graphicsComponent = object.getComponent(GraphicsComponent.class); dirtyRect.add(graphicsComponent.getDirtyRect()); } gameView_.repaint(dirtyRect); } /** * Method: renderGameView * Renders the game objects onto the game view. * @param g The graphics object that draws the game objects. */ public void renderGameView(Graphics g) { for (GameObject object : getRenderableObjects()) { GraphicsComponent graphicsComponent = object.getComponent(GraphicsComponent.class); if (!graphicsComponent.isVisible()) continue; GraphicsComponent.Shape shape = graphicsComponent.getShape(); BoundsComponent boundsComponent = object.getComponent(BoundsComponent.class); Rectangle bounds = boundsComponent.getBounds(); g.setColor(graphicsComponent.getColor()); if (shape == GraphicsComponent.Shape.RECTANGULAR) { g.fill3DRect(bounds.x, bounds.y, bounds.width, bounds.height, true); } else if (shape == GraphicsComponent.Shape.CIRCULAR) { g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height); } } } /** * Method: getRenderableObjects * @return The renderable game objects. */ private HashSet<GameObject> getRenderableObjects() { return gameManager.getGameObjectManager().getRelevantObjects( getClass()); } } Also all the updating in my game is event-driven. I don't have a loop like theirs that simply updates everything at the same time. I like my framework because it makes it easy to add new GameObjects, but doesn't have the problems some component-based designs encounter when communicating between components. I would hate to chuck it just to get pause to work. Is there a way I can add game states to my game without removing the entity-component design? Does the game state example actually fit my framework, and I'm just missing something?

    Read the article

  • Character with several colliders and rigidbodies

    - by Lautaro
    I am doing a PvP fighting game. This is the GameObject hierarchy of the player character. Player contains: Legs Sword Torso Head I want to be able to Register impacts of the sword on a specific body part Use AddForce on the whole player entity when a body part is struck Change the animation of the player that owns the sword that hit Questions Is it correct that the only rigidbody should be on the root Player GameObject ? Is it correct that The body parts should have colliders and be triggers ? Is it correct that The swords should have colliders but not be trigger ?

    Read the article

  • Can't change color of sprites in unity

    - by Aceleeon
    I would like to create a script that targets a 2d sprite "enemy" and changes their color to red (slightly opaque red if possible) when you hit tab. I have this code from a 3d tutorial hoping the transition would work. But it does not. I only get the script to cycle the enemy tags but never changes the color of the sprite. I have the code below I'm very new to coding, and any help would be FANTASTIC! HELP! hahah. TL;DR Cant get 3d color targeting to work for 2D. Check out the c#code below using UnityEngine; using System.Collections; using System.Collections.Generic; public class Targetting : MonoBehaviour { public List targets; public Transform selectedTarget; private Transform myTransform; // Use this for initialization void Start () { targets = new List(); selectedTarget = null; myTransform = transform; AddAllEnemies(); } public void AddAllEnemies() { GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy"); foreach(GameObject enemy in go) AddTarget(enemy.transform); } public void AddTarget(Transform enemy) { targets.Add(enemy); } private void SortTargetsByDistance() { targets.Sort(delegate(Transform t1,Transform t2) { return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position)); }); } private void TargetEnemy() { if(selectedTarget == null) { SortTargetsByDistance(); selectedTarget = targets[0]; } else { int index = targets.IndexOf(selectedTarget); if(index < targets.Count -1) { index++; } else { index = 0; } selectedTarget = targets[index]; } } private void SelectTarget() { selectedTarget.GetComponent().color = Color.red; } private void DeselectTarget() { selectedTarget.GetComponent().color = Color.blue; selectedTarget = null; } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.Tab)) { TargetEnemy(); } } }

    Read the article

  • C++ property system interface for game editors (reflection system)

    - by Cristopher Ismael Sosa Abarca
    I have designed an reusable game engine for an project, and their functionality is like this: Is a completely scripted game engine instead of the usual scripting languages as Lua or Python, this uses Runtime-Compiled C++, and an modified version of Cistron (an component-based programming framework).to be compatible with Runtime-Compiled C++ and so on. Using the typical GameObject and Component classes of the Component-based design pattern, is serializable via JSON, BSON or Binary useful for selecting which objects will be loaded the next time. The main problem: We want to use our custom GameObjects and their components properties in our level editor, before used hardcoded functions to access GameObject base class virtual functions from the derived ones, if do you want to modify an property specifically from that class you need inside into the code, this situation happens too with the derived classes of Component class, in little projects there's no problem but for larger projects becomes tedious, lengthy and error-prone. I've researched a lot to find a solution without luck, i tried with the Ogitor's property system (since our engine is Ogre-based) but we find it inappropiate for the component-based design and it's limited only for the Ogre classes and can lead to performance overhead, and we tried some code we find in the Internet we tested it and worked a little but we considered the macro and lambda abuse too horrible take a look (some code omitted): IWE_IMPLEMENT_PROP_BEGIN(CBaseEntity) IWE_PROP_LEVEL_BEGIN("Editor"); IWE_PROP_INT_S("Id", "Internal id", m_nEntID, [](int n) {}, true); IWE_PROP_LEVEL_END(); IWE_PROP_LEVEL_BEGIN("Entity"); IWE_PROP_STRING_S("Mesh", "Mesh used for this entity", m_pModelName, [pInst](const std::string& sModelName) { pInst->m_stackMemUndoType.push(ENT_MEM_MESH); pInst->m_stackMemUndoStr.push(pInst->getModelName()); pInst->setModel(sModelName, false); pInst->saveState(); }, false); IWE_PROP_VECTOR3_S("Position", m_vecPosition, [pInst](float fX, float fY, float fZ) { pInst->m_stackMemUndoType.push(ENT_MEM_POSITION); pInst->m_stackMemUndoVec3.push(pInst->getPosition()); pInst->saveState(); pInst->m_vecPosition.Get()[0] = fX; pInst->m_vecPosition.Get()[1] = fY; pInst->m_vecPosition.Get()[2] = fZ; pInst->setPosition(pInst->m_vecPosition); }, false); IWE_PROP_QUATERNION_S("Orientation (Quat)", m_quatOrientation, [pInst](float fW, float fX, float fY, float fZ) { pInst->m_stackMemUndoType.push(ENT_MEM_ROTATE); pInst->m_stackMemUndoQuat.push(pInst->getOrientation()); pInst->saveState(); pInst->m_quatOrientation.Get()[0] = fW; pInst->m_quatOrientation.Get()[1] = fX; pInst->m_quatOrientation.Get()[2] = fY; pInst->m_quatOrientation.Get()[3] = fZ; pInst->setOrientation(pInst->m_quatOrientation); }, false); IWE_PROP_LEVEL_END(); IWE_IMPLEMENT_PROP_END() We are finding an simplified way to this, without leading confusing the programmers, (will be released to the public) i find ways to achieve this but they are only available for the common scripting as Lua or editors using C#. also too portable, we can write "wrappers" for different GUI toolkits as Qt or GTK, also i'm thinking to using Boost.Wave to get additional macro functionality without creating my own compiler. The properties designed to use in the editor they are removed in the game since the save file contains their data and loads it using an simple 'load' function to reduce unnecessary code bloat may will be useful if some GameObject property wants to be hidden instead. In summary, there's a way to implement an reflection(property) system for a level editor based in properties from derived classes? Also we can use C++11 and Boost (restricted only to Wave and PropertyTree)

    Read the article

  • BlockingCollection having issues with byte arrays

    - by MJLaukala
    I am having an issue where an object with a byte[20] is being passed into a BlockingCollection on one thread and another thread returning the object with a byte[0] using BlockingCollection.Take(). I think this is a threading issue but I do not know where or why this is happening considering that BlockingCollection is a concurrent collection. Sometimes on thread2, myclass2.mybytes equals byte[0]. Any information on how to fix this is greatly appreciated. MessageBuffer.cs public class MessageBuffer : BlockingCollection<Message> { } In the class that has Listener() and ReceivedMessageHandler(object messageProcessor) private MessageBuffer RecievedMessageBuffer; On Thread1 private void Listener() { while (this.IsListening) { try { Message message = Message.ReadMessage(this.Stream, this); if (message != null) { this.RecievedMessageBuffer.Add(message); } } catch (IOException ex) { if (!this.Client.Connected) { this.OnDisconnected(); } else { Logger.LogException(ex.ToString()); this.OnDisconnected(); } } catch (Exception ex) { Logger.LogException(ex.ToString()); this.OnDisconnected(); } } } Message.ReadMessage(NetworkStream stream, iTcpConnectClient client) public static Message ReadMessage(NetworkStream stream, iTcpConnectClient client) { int ClassType = -1; Message message = null; try { ClassType = stream.ReadByte(); if (ClassType == -1) { return null; } if (!Message.IDTOCLASS.ContainsKey((byte)ClassType)) { throw new IOException("Class type not found"); } message = Message.GetNewMessage((byte)ClassType); message.Client = client; message.ReadData(stream); if (message.Buffer.Length < message.MessageSize + Message.HeaderSize) { return null; } } catch (IOException ex) { Logger.LogException(ex.ToString()); throw ex; } catch (Exception ex) { Logger.LogException(ex.ToString()); //throw ex; } return message; } On Thread2 private void ReceivedMessageHandler(object messageProcessor) { if (messageProcessor != null) { while (this.IsListening) { Message message = this.RecievedMessageBuffer.Take(); message.Reconstruct(); message.HandleMessage(messageProcessor); } } else { while (this.IsListening) { Message message = this.RecievedMessageBuffer.Take(); message.Reconstruct(); message.HandleMessage(); } } } PlayerStateMessage.cs public class PlayerStateMessage : Message { public GameObject PlayerState; public override int MessageSize { get { return 12; } } public PlayerStateMessage() : base() { this.PlayerState = new GameObject(); } public PlayerStateMessage(GameObject playerState) { this.PlayerState = playerState; } public override void Reconstruct() { this.PlayerState.Poisiton = this.GetVector2FromBuffer(0); this.PlayerState.Rotation = this.GetFloatFromBuffer(8); base.Reconstruct(); } public override void Deconstruct() { this.CreateBuffer(); this.AddToBuffer(this.PlayerState.Poisiton, 0); this.AddToBuffer(this.PlayerState.Rotation, 8); base.Deconstruct(); } public override void HandleMessage(object messageProcessor) { ((MessageProcessor)messageProcessor).ProcessPlayerStateMessage(this); } } Message.GetVector2FromBuffer(int bufferlocation) This is where the exception is thrown because this.Buffer is byte[0] when it should be byte[20]. public Vector2 GetVector2FromBuffer(int bufferlocation) { return new Vector2( BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation), BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation + 4)); }

    Read the article

  • C#: Delegate syntax?

    - by Rosarch
    I'm developing a game. I want to have game entities each have their own Damage() function. When called, they will calculate how much damage they want to do: public class CombatantGameModel : GameObjectModel { public int Health { get; set; } /// <summary> /// If the attack hits, how much damage does it do? /// </summary> /// <param name="randomSample">A random value from [0 .. 1]. Use to introduce randomness in the attack's damage.</param> /// <returns>The amount of damage the attack does</returns> public delegate int Damage(float randomSample); public CombatantGameModel(GameObjectController controller) : base(controller) {} } public class CombatantGameObject : GameObjectController { private new readonly CombatantGameModel model; public new virtual CombatantGameModel Model { get { return model; } } public CombatantGameObject() { model = new CombatantGameModel(this); } } However, when I try to call that method, I get a compiler error: /// <summary> /// Calculates the results of an attack, and directly updates the GameObjects involved. /// </summary> /// <param name="attacker">The aggressor GameObject</param> /// <param name="victim">The GameObject under assault</param> public void ComputeAttackUpdate(CombatantGameObject attacker, CombatantGameObject victim) { if (worldQuery.IsColliding(attacker, victim, false)) { victim.Model.Health -= attacker.Model.Damage((float) rand.NextDouble()); // error here Debug.WriteLine(String.Format("{0} hits {1} for {2} damage", attacker, victim, attackTraits.Damage)); } } The error is: 'Damage': cannot reference a type through an expression; try 'HWAlphaRelease.GameObject.CombatantGameModel.Damage' instead What am I doing wrong?

    Read the article

  • Obj-C component-based game architecture and message forwarding

    - by WanderWeird
    Hello, I've been trying to implement a simple component-based game object architecture using Objective-C, much along the lines of the article 'Evolve Your Hierarchy' by Mick West. To this end, I've successfully used a some ideas as outlined in the article 'Objective-C Message Forwarding' by Mike Ash, that is to say using the -(id)forwardingTargetForSelector: method. The basic setup is I have a container GameObject class, that contains three instances of component classes as instance variables: GCPositioning, GCRigidBody, and GCRendering. The -(id)forwardingTargetForSelector: method returns whichever component will respond to the relevant selector, determined using the -(BOOL)respondsToSelector: method. All this, in a way, works like a charm: I can call a method on the GameObject instance of which the implementation is found in one of the components, and it works. Of course, the problem is that the compiler gives 'may not respond to ...' warnings for each call. Now, my question is, how do I avoid this? And specifically regarding the fact that the point is that each instance of GameObject will have a different set of components? Maybe a way to register methods with the container objects, on a object per object basis? Such as, can I create some kind of -(void)registerMethodWithGameObject: method, and how would I do that? Now, it may or may not be obvious that I'm fairly new to Cocoa and Objective-C, and just horsing around, basically, and this whole thing may be very alien here. Of course, though I would very much like to know of a solution to my specific issue, anyone who would care to explain a more elegant way of doing this would additionally be very welcome. Much appreciated, -Bastiaan

    Read the article

  • accessing a method from a button within a class?

    - by flo
    #import "GameObject.h" #import "Definitions.h" @implementation GameObject @synthesize owner; @synthesize state; @synthesize mirrored; @synthesize button; @synthesize switcher; - (id) init { if ( self = [super init] ) { [self setOwner: EmptyField]; button = [UIButton buttonWithType:UIButtonTypeCustom]; [self setSwitcher: FALSE]; } return self; } - (UIButton*) display{ button.frame = CGRectMake(0, 0, GO_Width, GO_Height); [button setBackgroundImage:[UIImage imageNamed:BlueStone] forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; return button; } -(void)buttonPressed:(id) sender { //... } } - (void) dealloc { [super dealloc]; } @end Hi! i would like to know if the above is possible somehow within a class (in my case it is called GameObject) or if i HAVE to have the button call a methode in the viewcontroller... the above results with the app crashing. i would call display within a loop on the viewcontroller and id like to change some of the GameObjects instance variables within buttonPressed. Also id like to change some other stuff by calling some other methods from within buttonPressed but i think that will be the lesser of my problems ;) also id like to know how i can pass some variables to the buttonPressed method... cant find it anywhere :( help on this one would be much appreciated ;) thanks flo

    Read the article

  • Tile Engine - Procedural generation, Data structures, Rendering methods - A lot of effort question!

    - by Trixmix
    Isometric Tile and GameObject rendering. To achive the desired looking game I need to take into consideration which tiles need to be drawn first and which last. What I used is a Object that is TileRenderQueue that you would give it a tile list and it will give you a queue on which ones to draw based on their Z coordinate, so that if the Z is higher then it needs to be drawn last. Now if you read above you would know that I want the location data to instead of being stored in the tile instance i want it to be that the index in the array is the location. and then maybe based on the array i could draw the tiles instead of taking a long time in for looping and ordering them by Z. This is the hardest part for me. It's hard for me to find a simple solution to the which one to draw when problem. Also there is the fact that if the X is larger than the gameobject where the X is larger needs to be drawn over the rest of the tiles and so on. Here is an example: All the parts work together to create an efficient engine so its important to me that you would answer all of the parts. I hope you will work on the answers hard just as much that I worked on this question! If there is any unclear part tell me so in the comments! Thanks for the help!

    Read the article

  • Box Collider isn't rotating with Game Object

    - by pek
    I have a method that creates a room by instantiating a prefab, places it in a grid and the re-sizes the collider based on a room definition (location in grid, rotation, width and height). Here is the method: public void CreateRoom(RoomAction action) { GameObject roomGameObject = Instantiate(this.roomPrefab, Vector3.zero, action.RoomPrefab.transform.rotation) as GameObject; roomGameObject.transform.parent = this.transform; roomGameObject.transform.localPosition = new Vector3(action.MansionOffsetX, 0, -action.MansionOffsetY) * this.blockSize; roomGameObject.transform.localPosition += new Vector3((action.Room.Width * this.blockSize) / 2, 0, -((action.Room.Height * this.blockSize) / 2)); BoxCollider roomCollider = roomGameObject.GetComponent<BoxCollider>(); roomCollider.isTrigger = true; roomCollider.center = new Vector3(0, this.height / 2, 0); roomCollider.size = new Vector3(action.Room.Width * this.blockSize, this.height, action.Room.Height * this.blockSize); roomGameObject.transform.RotateAroundLocal(roomGameObject.transform.up, Mathf.Deg2Rad * -90 * action.Rotation); } The problem I'm having is that, while the room rotates correctly, but for some reason, the collider isn't rotating with the game object. Here is a screenshot: Any idea on what am I doing wrong?

    Read the article

  • Scale a game object to Bounds

    - by Spikeh
    I'm trying to scale a lot of dynamically created game objects in Unity3D to the bounds of a sphere collider, based on the size of their current mesh. Each object has a different scale and mesh size. Some are bigger than the AABB of the collider, and some are smaller. Here's the script I've written so far: private void ScaleToCollider(GameObject objectToScale, SphereCollider sphere) { var currentScale = objectToScale.transform.localScale; var currentSize = objectToScale.GetMeshHierarchyBounds().size; var targetSize = (sphere.radius * 2); var newScale = new Vector3 { x = targetSize * currentScale.x / currentSize.x, y = targetSize * currentScale.y / currentSize.y, z = targetSize * currentScale.z / currentSize.z }; Debug.Log("{0} Current scale: {1}, targetSize: {2}, currentSize: {3}, newScale: {4}, currentScale.x: {5}, currentSize.x: {6}", objectToScale.name, currentScale, targetSize, currentSize, newScale, currentScale.x, currentSize.x); //DoorDevice_meshBase Current scale: (0.1, 4.0, 3.0), targetSize: 5, currentSize: (2.9, 4.0, 1.1), newScale: (0.2, 5.0, 13.4), currentScale.x: 0.125, currentSize.x: 2.869114 //RedControlPanelForAirlock_meshBase Current scale: (1.0, 1.0, 1.0), targetSize: 5, currentSize: (0.0, 0.3, 0.2), newScale: (147.1, 16.7, 25.0), currentScale.x: 1, currentSize.x: 0.03400017 objectToScale.transform.localScale = newScale; } And the supporting extension method: public static Bounds GetMeshHierarchyBounds(this GameObject go) { var bounds = new Bounds(); // Not used, but a struct needs to be instantiated if (go.renderer != null) { bounds = go.renderer.bounds; // Make sure the parent is included Debug.Log("Found parent bounds: " + bounds); //bounds.Encapsulate(go.renderer.bounds); } foreach (var c in go.GetComponentsInChildren<MeshRenderer>()) { Debug.Log("Found {0} bounds are {1}", c.name, c.bounds); if (bounds.size == Vector3.zero) { bounds = c.bounds; } else { bounds.Encapsulate(c.bounds); } } return bounds; } After the re-scale, there doesn't seem to be any consistency to the results - some objects with completely uniform scales (x,y,z) seem to resize correctly, but others don't :| Its one of those things I've been trying to fix for so long I've lost all grasp on any of the logic :| Any help would be appreciated!

    Read the article

  • Unity3d: calculate the result of a transform without modifying transform object itself

    - by Heisenbug
    I'm in the following situation: I need to move an object in some way, basically rotating it around its parent local position, or translating it in its parent local space (I know how to do this). The amount of rotation and translation is know at runtime (it depends on several factors, the speed of the object, enviroment factors, etc..). The problem is the following: I can perform this transformation only if the result position of the transformed object fit some criterias. An example could be this: the distance between the position before and after the transformation must be less than a given threshold. (Actually the conditions could be several and more complex) The problem is that if I use Transform.Rotate and Transform.Translate methods of my GameObject, I will loose the original Transform values. I think I can't copy the original Transform using instantiate for performance issues. How can I perform such a task? I think I have more or less 2 possibilities: First Don't modify the GameObject position through Transform. Calculate which will be the position after the transform. If the position is legal, modify transform through Translate and Rotate methods Second Store the original transform someway. Transform the object using Translate and Rotate. If the transformed position is illegal, restore the original one.

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >