Search Results

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

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

  • Unity3D: How to make the camera focus a moving game object with ITween?

    - by nathan
    I'm trying to write a solar system with Unity3D. Planets are sphere game objects rotating around another sphere game object representing the star. What i want to achieve is let the user click on a planet and then zoom the camera on this planet and then make the camera follow and keep it centered on the screen while it keep moving around the star. I decided to use iTween library and so far i was able to create the zoom effect using iTween.MoveUpdate. My problem is that the focused planet does not say properly centered as it moves. Here is the relevant part of my script: void Update () { if (Input.GetButtonDown("Fire1")) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity, concernedLayers)) { selectedPlanet = hit.collider.gameObject; } } } void LateUpdate() { if (selectedPlanet != null) { Vector3 pos = selectedPlanet.transform.position; pos.z = selectedPlanet.transform.position.z - selectedPlanet.transform.localScale.z; pos.y = selectedPlanet.transform.position.y; iTween.MoveUpdate(Camera.main.gameObject, pos, 2); } } What do i need to add to this script to make the selected planet stay centered on the screen? I hosted my current project as a webplayer application so you see what's going wrong. You can access it here.

    Read the article

  • Relative encapsulation design

    - by taher1992
    Let's say I am doing a 2D application with the following design: There is the Level object that manages the world, and there are world objects which are entities inside the Level object. A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes. But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation). How to tackle this problem? Should I just make everything public? Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this: void ChangeObject(GameObject targetObject, int newX, int newY){ // targetObject.SetX and targetObject.SetY cannot be set directly var setter = new GameObject.Setter(targetObject); setter.SetX(newX); setter.SetY(newY); } This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.

    Read the article

  • Shooter in iOS and a visible Aim line before shooting

    - by London2423
    I have to questions. I am trying to develop a game that is iOS but I did it first in my computer so I can tested there. I was able to must of it for PC but I am having a very hard time with iOS port The problem I do have is that I don't know how to shout in iOS. To be more specific how to line render in iOS This is the script I use in my computer using UnityEngine; using System.Collections; public class NewBehaviourScript : MonoBehaviour { LineRenderer line; void Start () { line = gameObject.GetComponent<LineRenderer>(); line.enabled = false; } void Update () { if (Input.GetButtonDown ("Fire1")) { StopCoroutine ("FireLaser"); StartCoroutine ("FireLaser"); } } IEnumerator FireLaser () { line.enabled = true; while (Input.GetButton("Fire1")) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; line.SetPosition (0, ray.origin); if (Physics.Raycast (ray, out hit,100)) { line.SetPosition(1,hit.point); if (hit.rigidbody) { hit.rigidbody.AddForceAtPosition(transform.forward * 5, hit.point); } } else line.SetPosition (1, ray.GetPoint (100)); yield return null; } line.enabled = false; { } } } Which part I have to change for iOS? I already did in the iOS the touch giu event so my player move around in the xcode/Iphone but I need some help with the shouting part. The second part of the question is where I do have to insert or change the script in order to first aim and I DO see the line of aim and then shout. Now the player can only shout. It can not aim at the gameobject, see the the line coming out of the gun aiming at the object and then shout? How I can do that. Everyone tell me Line render but that's what i did Thank you

    Read the article

  • How to structure game states in an entity/component-based system

    - 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? EDIT: I might not have explained my framework well enough. My components are just data. If I was coding in C++, they'd probably be structs. Here's an example of one: public class BoundsComponent implements GameComponent { /** * The position of the game object. */ private Point pos_; /** * The size of the game object. */ private Dimension size_; /** * Constructor * Creates a new BoundsComponent for a game object with initial position * initialPos and initial size initialSize. The position and size combine * to make up the bounds. * @param initialPos The initial position of the game object. * @param initialSize The initial size of the game object. */ public BoundsComponent(Point initialPos, Dimension initialSize) { pos_ = initialPos; size_ = initialSize; } /** * Method: getBounds * @return The bounds of the game object. */ public Rectangle getBounds() { return new Rectangle(pos_, size_); } /** * Method: setPos * Sets the position of the game object to newPos. * @param newPos The value to which the position of the game object is * set. */ public void setPos(Point newPos) { pos_ = newPos; } } My components do not communicate with each other. Systems handle inter-component communication. My systems also do not communicate with each other. They have separate functionality and can easily be kept separate. The MovementSystem doesn't need to know what the RenderingSystem is rendering to move the game objects correctly; it just need to set the right values on the components, so that when the RenderingSystem renders the game objects, it has accurate data. The game state could not be a system, because it needs to interact with the systems rather than the components. It's not setting data; it's determining which functions need to be called. A GameStateComponent wouldn't make sense because all the game objects share one game state. Components are what make up objects and each one is different for each different object. For example, the game objects cannot have the same bounds. They can have overlapping bounds, but if they share a BoundsComponent, they're really the same object. Hopefully, this explanation makes my framework less confusing.

    Read the article

  • ArgumentError: Error #2015: Invalid BitmapData.

    - by numerical25
    I am having problems loading a bitmapData. I am getting the following error Engine Init //trace loadimage//trace ArgumentError: Error #2015: Invalid BitmapData. at flash.display::BitmapData() Below is my code. it appears it happens after the trace loadimage package com.objects { import flash.display.Sprite; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Point; import flash.geom.Rectangle; import flash.display.Loader; import flash.net.URLRequest; import flash.net.*; import flash.events.*; import flash.display.LoaderInfo; public class gameObject extends Sprite { protected var w:Number; protected var h:Number; protected var image:BitmapData; protected var canvas:Bitmap; protected var px:Number; protected var py:Number; public function gameObject():void { init(); } private function init():void { } public function loadImage(imageDir:String, w:Number, h:Number, px:Number, py:Number):void { this.w = w; this.y = y; this.px = px; this.py = py; trace("loadimage"); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE,imageComplete); loader.load(new URLRequest(imageDir)); } private function imageComplete(e:Event):void { var loader:LoaderInfo = LoaderInfo(e.target); image = Bitmap(loader.content).bitmapData; drawImage(); } private function drawImage():void { var tilePoint:Point = new Point(0,0); var tileRect = new Rectangle(py,px,w,h); trace(loader.content); var canvasData:BitmapData = new BitmapData(w,h); trace("got canvas data"); canvasData.copyPixels(image,tileRect,tilePoint); trace("copied pixels"); canvas = new Bitmap(canvasData); } } } And my call the the method is like so balls = new Array(); balls[0] = new gameObject(); balls[0].loadImage("com/images/ball.gif", 15,15,0,0); When I trace the Loader.content, below is what shows Engine Init loadimage [object Bitmap] ArgumentError: Error #2015: Invalid BitmapData. at flash.display::BitmapData()

    Read the article

  • C++: Create abstract class with abstract method and override the method in a subclass

    - by Martijn Courteaux
    Hi, How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp, if so how should it look? In Java it would look like this: abstract class GameObject { public abstract void update(); public abstract void paint(Graphics g); } class Player extends GameObject { @Override public void update() { // ... } @Override public void paint(Graphics g) { // ... } } // In my game loop: for (int i = 0; i < objects.size(); i++) { objects.get(i).update(); } for (int i = 0; i < objects.size(); i++) { objects.get(i).paint(g); } Translating this code to C++ is enough for me.

    Read the article

  • Lua - How to use functions from another script

    - by Person
    I'm wondering how to use functions from another script in Lua. For example, say GameObjectUtilities holds functions that many GameObject scripts will use. The Slime (a GameObject) script wants to use a function in GameObjectUtilities. I'm having trouble getting this to work. I've looked here, but I still don't really fully understand. Do I need to create a module or a table to hold the functions in GameObjectUtilities for the functions in it to be used in other scripts? If so, what is the best way to go about this?

    Read the article

  • Filtering NSMutableArray based on enum property

    - by Marty
    I've got an NSMutableArray filled with objects of type "GameObject". GameObject has a number of properties, one of which being "gameObjectType" . "gameObjectType" is of type GameObjectTypeEnum. I want to be able to filter this NSMutableArray so only GameObjects of a certain type are returned. I've got the following in place, but it's giving me a "BAD ACCESS" error: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"gameObjectType = %@", gameObjectType]; return [gameObjects filteredArrayUsingPredicate:predicate]; Is it possible to pass a "custom" type (ie, this enum I've defined) into the predicateWithFormat call?

    Read the article

  • How to impale and stack targets correctly according to the collider and its coordinate?

    - by David Dimalanta
    I'm making another simple game, a catch game, where a spawning target game object must be captured using a skewer to impale it. Here how: At the start, the falling object (in red) will fall in a vertical direction (in blue) When aimed properly, the target will fall down along the line of the skewer. (in blue) Then, another target is spawned and will fall vertically. (in red) When aimed successfully again in a streak, the second target will fall along the skewer and stacked. Same process over and over when another target is spawned. However, when I test run it on the scene tab in Unity, when impaled several targets, instead of a smooth flow and stacking it ended up overlaying it instead of stacking it up like a pancake. Here's what it look like: As I noticed when reaching the half-way of my progress, I tried to figure out how to deal with collider bodies without sticking each other so that it will actually stack like in the example of the image at no. 3. Here's the script code I added in the target game object: using UnityEngine; using System.Collections; public class ImpaleStateTest : MonoBehaviour { public GameObject target; public GameObject skewer; public bool drag = false; private float stack; private float impaleCount; void Start () { stack = 0; impaleCount = 0; } void Update () { if(drag) { target.transform.position = new Vector3 (DragTest.dir.transform.position.x, DragTest.dir.transform.position.y - 0.35f, 0); target.transform.rotation = DragTest.degrees; target.rigidbody2D.fixedAngle = true; target.rigidbody2D.isKinematic = true; target.rigidbody2D.gravityScale = 0; if(Input.GetMouseButton(0)) { Debug.Log ("Skewer: " + DragTest.dir.transform.position.x); Debug.Log ("Target: " + target.transform.position.x); } } } void OnTriggerEnter2D(Collider2D collider) { impaleCount++; Debug.Log ("Impaled " + impaleCount + " time(s)!"); drag = true; audio.Play (); } } Aside from that, I'm not sure if it's right but, the only way to stick the impaled targets while dragging the skewer left or right is to get the X coordinates from the skewer only. Is there something else to recommend it in order to improve this behavior as realistic as possible? Please help.

    Read the article

  • Register Game Object Components in Game Subsystems? (Component-based Game Object design)

    - by topright
    I'm creating a component-based game object system. Some tips: GameObject is simply a list of Components. There are GameSubsystems. For example, rendering, physics etc. Each GameSubsystem contains pointers to some of Components. GameSubsystem is a very powerful and flexible abstraction: it represents any slice (or aspect) of the game world. There is a need in a mechanism of registering Components in GameSubsystems (when GameObject is created and composed). There are 4 approaches: 1: Chain of responsibility pattern. Every Component is offered to every GameSubsystem. GameSubsystem makes a decision which Components to register (and how to organize them). For example, GameSubsystemRender can register Renderable Components. pro. Components know nothing about how they are used. Low coupling. A. We can add new GameSubsystem. For example, let's add GameSubsystemTitles that registers all ComponentTitle and guarantees that every title is unique and provides interface to quering objects by title. Of course, ComponentTitle should not be rewrited or inherited in this case. B. We can reorganize existing GameSubsystems. For example, GameSubsystemAudio, GameSubsystemRender, GameSubsystemParticleEmmiter can be merged into GameSubsystemSpatial (to place all audio, emmiter, render Components in the same hierarchy and use parent-relative transforms). con. Every-to-every check. Very innefficient. con. Subsystems know about Components. 2: Each Subsystem searches for Components of specific types. pro. Better performance than in Approach 1. con. Subsystems still know about Components. 3: Component registers itself in GameSubsystem(s). We know at compile-time that there is a GameSubsystemRenderer, so let's ComponentImageRender will call something like GameSubsystemRenderer::register(ComponentRenderBase*). pro. Performance. No unnecessary checks as in Approach 1. con. Components are badly coupled with GameSubsystems. 4: Mediator pattern. GameState (that contains GameSubsystems) can implement registerComponent(Component*). pro. Components and GameSubystems know nothing about each other. con. In C++ it would look like ugly and slow typeid-switch. Questions: Which approach is better and mostly used in component-based design? What Practice says? Any suggestions about implementation of Approach 4? Thank you.

    Read the article

  • Simple collision detection in Unity 2D

    - by N1ghtshade3
    I realise other posts exist with this topic yet none have gone into enough detail for me. I am attempting to create a 2D game in Unity using C# as my scripting language. Basically I have two objects, player and bomb. Both were created simply by dragging the respective PNG to the stage. I have set up touch controls to move player left and right; gravity of any kind is not needed as I only require it to move x units when I tap either the left or right side of the screen. This movement is stored in a script called playerController.cs and works just fine. I also have a variable health = 3 for player, which is stored in healthScript.cs. I am now at a point where I am stuck. I would like it so that when player collides with bomb, health decreases by one and the bomb object is destroyed. So what I tried doing is using a new script called playerPhysics.cs, I added the following: void OnCollisionEnter2D(Collision2D coll){ if(coll.gameObject.name=="bomb") GameObject.Destroy("bomb"); healthScript.health -= 1; } While I'm fairly sure I don't know the proper way to reference a variable in another script and that's why the health didn't decrease when I collided, bomb never disappeared from the stage so I'm thinking there's also a problem with my collision. Initially, I had simply attached playerPhysics.cs to player. After searching around though, it appeared as though player also needed a rigidBody attached to it, so I did that. Still no luck. I tried using a circleCollider (player is a circle), using a rigidBody2D, and using all manner of colliders on one and/or both of the objects. If you could please explain what colliders (if any) should be attached to which objects and whether I need to change my script(s), that would be much more helpful than pointing me to one of the generic documentation examples I've already read. Also, if it would be simple to fix the health thing not working that would be an added bonus but not exactly the focus of this question. Bear in mind that this game is 2D; I'm not sure if that changes anything. Thanks!

    Read the article

  • change texture at runtime

    - by user1509674
    How can I change the texture at runtime. I have done changing the label(text) at runtime. The following code is used using UnityEngine; using System.Collections; public class switchtime : MonoBehaviour { // Use this for initialization private bool showLabel = false; private bool showLabe2 = false; private bool showLabe3 = false; private bool showLabe4 = false; public void Start() { Invoke("ToggleLabel", 1); Invoke("ToggleLabel2", 3); Invoke("ToggleLabel3",6 ); Invoke("ToggleLabel4", 9); } public void ToggleLabel() { showLabel = !showLabel; } public void ToggleLabel2() { showLabe2 = !showLabe2; } public void ToggleLabel3() { showLabe3 = !showLabe3; } public void ToggleLabel4() { showLabe4 = !showLabe4; } public void OnGUI() { if (showLabel) { GUI.Label(new Rect(300, 200, 100, 20), "Copying window file.."); } if (showLabe2) { GUI.Label(new Rect(40, 40, 100, 20), "Epanding windows file.."); } if (showLabe3) { GUI.Label(new Rect(80, 80, 100, 20), "Installing Feature.."); } if (showLabe4) { GUI.Label(new Rect(100, 100, 100, 20), "Installing Updates"); } } } Now I need to change the GUITexture at runtime. How can do this? Can anybody help me in coding? Here is some changes I made. I worked on changing the gameObject when mouse is placed on it. This is the code I applied and its working for me using UnityEngine; using System.Collections; public class change : MonoBehaviour { // Use this for initialization public GameObject newSprite; private Vector3 currentSpritePosition; void update() { } void Start() { newSprite.renderer.enabled = false; currentSpritePosition = transform.position; //then make it invisible renderer.enabled = false; //give the new sprite the position of the latter newSprite.transform.position = currentSpritePosition; //then make it visible newSprite.renderer.enabled = true; } void OnMouseExit(){ //just the reverse process renderer.enabled = true; newSprite.renderer.enabled = false; } } Now the problem is that, in same code I need to set a time so that the text get loaded without the mouse click. I mean a particular time to load each text one after the another. Here is my screen shot Here I have placed the image one below the another,when the mouse is hovered on it it will change the text from bold to normal text.Changes process stated in (image 2,3).That code I posted is working for me.

    Read the article

  • Why are my Unity procedural animations jerky?

    - by Phoenix Perry
    I'm working in Unity and getting some crazy weird motion behavior. I have a plane and I'm moving it. It's ever so slightly getting about 1 pixel bigger and smaller. It looks like the it's kind of getting squeezed sideways by a pixel. I'm moving a plane by cos and sin so it will spin on the x and z axes. If the planes are moving at Time.time, everything is fine. However, if I put in slower speed multiplier, I get an amazingly weird jerk in my animation. I get it with or without the lerp. How do I fix it? I want it to move very slowly. Is there some sort of invisible grid in unity? Some sort of minimum motion per frame? I put a visual sample of the behavior here. Here's the relevant code: public void spin() { for (int i = 0; i < numPlanes; i++ ) { GameObject g = planes[i] as GameObject; //alt method //currentRotation += speed * Time.deltaTime * 100; //rotation.eulerAngles = new Vector3(0, currentRotation, 0); //g.transform.position = rotation * rotationRadius; //sine method g.GetComponent<PlaneSetup>().pos.x = g.GetComponent<PlaneSetup>().radiusX * (Mathf.Cos((Time.time*speed) + g.GetComponent<PlaneSetup>().startAngle)); g.GetComponent<PlaneSetup>().pos.z = g.GetComponent<PlaneSetup>().radius * Mathf.Sin((Time.time*speed) + g.GetComponent<PlaneSetup>().startAngle); g.GetComponent<PlaneSetup>().pos.y = g.GetComponent<Transform>().position.y; ////offset g.GetComponent<PlaneSetup>().pos.z += 20; g.GetComponent<PlaneSetup>().posLerp.x = Mathf.Lerp(g.transform.position.x,g.GetComponent<PlaneSetup>().pos.x, .5f); g.GetComponent<PlaneSetup>().posLerp.z = Mathf.Lerp(g.transform.position.z, g.GetComponent<PlaneSetup>().pos.z, .5f); g.GetComponent<PlaneSetup>().posLerp.y = g.GetComponent<Transform>().position.y; g.transform.position = g.GetComponent<PlaneSetup>().posLerp; } Invoke("spin",0.0f); } The full code is on github. There is literally nothing else going on. I've turned off all other game objects so it's only the 40 planes with a texture2D shader. I removed it from Invoke and tried it in Update -- still happens. With a set frame rate or not, the same problem occurs. Tested it in Fixed Update. Same issue. The script on the individual plane doesn't even have an update function in it. The data on it could functionally live in a struct. I'm getting between 90 and 123 fps. Going to investigate and test further. I put this in an invoke function to see if I could get around it just occurring in update. There are no physics on these shapes. It's a straight procedural animation. Limited it to 1 plane - still happens. Thoughts? Removed the shader - still happening.

    Read the article

  • Problem with boundary collision

    - by James Century
    The problem: When the player hits the left boundary he stops (this is exactly what I want), when he hits the right boundary. He continues until his rectangle's left boundary meets with the right boundary. Outcome: https://www.youtube.com/watch?v=yuJfIWZ_LL0&feature=youtu.be My Code public class Player extends GameObject{ BufferedImageLoader loader; Texture tex = Game.getInstance(); BufferedImage image; Animation playerWalkLeft; private HealthBarManager healthBar; private String username; private int width; private ManaBarManager manaBar; public Player(float x, float y, ObjectID ID) { super(x, y, ID, null); loader = new BufferedImageLoader(); playerWalkLeft = new Animation(5,tex.player[10],tex.player[11],tex.player[12],tex.player[13],tex.player[14],tex.player[15],tex.player[17],tex.player[18]); } public void tick(LinkedList<GameObject> object) { setX(getX()+velX); setY(getY()+velY); playerWalkLeft.runAnimation(); } public void render(Graphics g) { g.setColor(Color.BLACK); FontMetrics fm = g.getFontMetrics(g.getFont()); if(username != null) width = fm.stringWidth(username); if(username != null){ g.drawString(username,(int) x-width/2+15,(int) y); } if(velX != 0){ playerWalkLeft.drawAnimation(g, (int)x, (int)y); }else{ g.drawImage(tex.player[16], (int)x, (int)y, null); } g.setColor(Color.PINK); g.drawRect((int)x,(int)y,33,48); g.drawRect(0,0,(int)Game.getWalkableBounds().getWidth(), (int)Game.getWalkableBounds().getHeight()); } @SuppressWarnings("unused") private Image getCurrentImage() { return image; } public float getX() { return x; } public float getY() { return y; } public void setX(float x) { Rectangle gameBoundry = Game.getWalkableBounds(); if(x >= gameBoundry.getMinX() && x <= gameBoundry.getMaxX()){ this.x = x; } } public void setY(float y) { //IGNORE THE SetY please. this.y = y; } public float getVelX() { return velX; } public void setHealthBar(HealthBarManager healthBar){ this.healthBar = healthBar; } public HealthBarManager getHealthBar(){ return healthBar; } public float getVelY() { return velY; } public void setVelX(float velX) { this.velX = velX; } public void setVelY(float velY) { this.velY = velY; } public ObjectID getID() { return ID; } public void setUsername(String playerName) { this.username = playerName; } public String getUsername(){ return this.username; } public void setManaBar(ManaBarManager manaBar) { this.manaBar = manaBar; } public ManaBarManager getManaBar(){ return manaBar; } public int getLevel(){ return 1; } public boolean isPlayerInsideBoundry(float x, float y){ Rectangle boundry = Game.getWalkableBounds(); if(boundry.contains(x,y)){ return true; } return false; } } What I've tried: - Using a method that checks if the game boundary contains player boundary rectangle. This gave me the same result as what the check statement in my setX did.

    Read the article

  • Resolving collisions between dynamic game objects

    - by TheBroodian
    I've been building a 2D platformer for some time now, I'm getting to the point where I am adding dynamic objects to the stage for testing. This has prompted me to consider how I would like my character and other objects to behave when they collide. A typical staple in many 2D platformer type games is that the player takes damage upon touching an enemy, and then essentially becomes able to pass through enemies during a period of invulnerability, and at the same time, enemies are able to pass through eachother freely. I personally don't want to take this approach, it feels strange to me that the player should receive arbitrary damage for harmless contact to an enemy, despite whether the enemy is attacking or not, and I would like my enemies' interactions between each other (and my player) to be a little more organic, so to speak. In my head I sort of have this idea where a game object (player, or non player) would be able to push other game objects around by manner of 'pushing' each other out of one anothers' bounding boxes if there is an intersection, and maybe correlate the repelling force to how much their bounding boxes are intersecting. The problem I'm experiencing is I have no idea what the math might look like for something like this? I'll show what work I've done so far, it sort of works, but it's jittery, and generally not quite what I would pass in a functional game: //Clears the anti-duplicate buffer collisionRecord.Clear(); //pick a thing foreach (GameObject entity in entities) { //pick another thing foreach (GameObject subject in entities) { //check to make sure both things aren't the same thing if (!ReferenceEquals(entity, subject)) { //check to see if thing2 is in semi-near proximity to thing1 if (entity.WideProximityArea.Intersects(subject.CollisionRectangle) || entity.WideProximityArea.Contains(subject.CollisionRectangle)) { //check to see if thing2 and thing1 are colliding. if (entity.CollisionRectangle.Intersects(subject.CollisionRectangle) || entity.CollisionRectangle.Contains(subject.CollisionRectangle) || subject.CollisionRectangle.Contains(entity.CollisionRectangle)) { //check if we've already resolved their collision or not. if (!collisionRecord.ContainsKey(entity.GetHashCode())) { //more duplicate resolution checking. if (!collisionRecord.ContainsKey(subject.GetHashCode())) { //if thing1 is traveling right... if (entity.Velocity.X > 0) { //if it isn't too far to the right... if (subject.CollisionRectangle.Contains(new Microsoft.Xna.Framework.Rectangle(entity.CollisionRectangle.Right, entity.CollisionRectangle.Y, 1, entity.CollisionRectangle.Height)) || subject.CollisionRectangle.Intersects(new Microsoft.Xna.Framework.Rectangle(entity.CollisionRectangle.Right, entity.CollisionRectangle.Y, 1, entity.CollisionRectangle.Height))) { //Find how deep thing1 is intersecting thing2's collision box; float offset = entity.CollisionRectangle.Right - subject.CollisionRectangle.Left; //Move both things in opposite directions half the length of the intersection, pushing thing1 to the left, and thing2 to the right. entity.Velocities.Add(new Vector2(-(((offset * 4) * (float)gameTime.ElapsedGameTime.TotalMilliseconds)), 0)); subject.Velocities.Add(new Vector2((((offset * 4) * (float)gameTime.ElapsedGameTime.TotalMilliseconds)), 0)); } } //if thing1 is traveling left... if (entity.Velocity.X < 0) { //if thing1 isn't too far left... if (entity.CollisionRectangle.Contains(new Microsoft.Xna.Framework.Rectangle(subject.CollisionRectangle.Right, subject.CollisionRectangle.Y, 1, subject.CollisionRectangle.Height)) || entity.CollisionRectangle.Intersects(new Microsoft.Xna.Framework.Rectangle(subject.CollisionRectangle.Right, subject.CollisionRectangle.Y, 1, subject.CollisionRectangle.Height))) { //Find how deep thing1 is intersecting thing2's collision box; float offset = subject.CollisionRectangle.Right - entity.CollisionRectangle.Left; //Move both things in opposite directions half the length of the intersection, pushing thing1 to the right, and thing2 to the left. entity.Velocities.Add(new Vector2((((offset * 4) * (float)gameTime.ElapsedGameTime.TotalMilliseconds)), 0)); subject.Velocities.Add(new Vector2(-(((offset * 4) * (float)gameTime.ElapsedGameTime.TotalMilliseconds)), 0)); } } //Make record that thing1 and thing2 have interacted and the collision has been solved, so that if thing2 is picked next in the foreach loop, it isn't checked against thing1 a second time before the next update. collisionRecord.Add(entity.GetHashCode(), subject.GetHashCode()); } } } } } } } } One of the biggest issues with my code aside from the jitteriness is that if one character were to land on top of another character, it very suddenly and abruptly resolves the collision, whereas I would like a more subtle and gradual resolution. Any thoughts or ideas are incredibly welcome and helpful.

    Read the article

  • Box2d: Set active and inactive

    - by Rosarch
    I'm writing an XNA game in C# using the XNA port of Box2d - Box2dx. Entities like trees or zombies are represented as GameObjects. GameObjectManager adds and removes them from the game world: /// <summary> /// Does the work of removing the GameObject. /// </summary> /// <param name="controller">The GameObject to be removed.</param> private void removeGameObjectFromWorld(GameObjectController controller) { controllers.Remove(controller); worldState.Models.Remove(controller.Model); controller.Model.Body.SetActive(false); } public void addGameObjectToWorld(GameObjectController controller) { controllers.Add(controller); worldState.Models.Add(controller.Model); controller.Model.Body.SetActive(true); } controllers is a collection of GameObjectController instances. worldState.Models is a collection of GameObjectModel instances. When I remove GameObjects from Box2d this way, this method gets called: void IContactListener.EndContact(Contact contact) { GameObjectController collider1 = worldQueryUtils.gameObjectOfBody(contact.GetFixtureA().GetBody()); GameObjectController collider2 = worldQueryUtils.gameObjectOfBody(contact.GetFixtureB().GetBody()); collisionRecorder.removeCollision(collider1, collider2); } worldQueryUtils: // this could be cached if we know bodies never change public GameObjectController gameObjectOfBody(Body body) { return worldQueryEngine.GameObjectsForPredicate(x => x.Model.Body == body).Single(); } This method throws an error: System.InvalidOperationException was unhandled Message="Sequence contains no elements" Source="System.Core" StackTrace: at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source) at etc Why is this happening? What can I do to avoid it? This method has been called many times before the body.SetActive() was called. I feel that this may be messing it up.

    Read the article

  • Box2dx: Usage of World.QueryAABB?

    - by Rosarch
    I'm using Box2dx with C#/XNA. I'm trying to write a function that determines if a body could exist in a given point without colliding with anything: /// <summary> /// Can gameObject exist with start Point without colliding with anything? /// </summary> internal bool IsAvailableArea(GameObjectModel model, Vector2 point) { Vector2 originalPosition = model.Body.Position; model.Body.Position = point; // less risky would be to use a deep clone AABB collisionBox; model.Body.GetFixtureList().GetAABB(out collisionBox); // how is this supposed to work? physicsWorld.QueryAABB(x => true, ref collisionBox); model.Body.Position = originalPosition; return true; } Is there a better way to go about doing this? How is World.QueryAABB supposed to work? Here is an earlier attempt. It is broken; it always returns false. /// <summary> /// Can gameObject exist with start Point without colliding with anything? /// </summary> internal bool IsAvailableArea(GameObjectModel model, Vector2 point) { Vector2 originalPosition = model.Body.Position; model.Body.Position = point; // less risky would be to use a deep clone AABB collisionBox; model.Body.GetFixtureList().GetAABB(out collisionBox); ICollection<GameObjectController> gameObjects = worldQueryEngine.GameObjectsForPredicate(x => ! x.Model.Passable); foreach (GameObjectController controller in gameObjects) { AABB potentialCollidingBox; controller.Model.Body.GetFixtureList().GetAABB(out potentialCollidingBox); if (AABB.TestOverlap(ref collisionBox, ref potentialCollidingBox)) { model.Body.Position = originalPosition; return false; // there is something that will collide at this point } } model.Body.Position = originalPosition; return true; }

    Read the article

  • How would I go about sharing variables in a class with Lua?

    - by Nicholas Flynt
    I'm fairly new to Lua, I've been working on trying to implement Lua scripting for logic in a Game Engine I'm putting together. I've had no trouble so far getting Lua up and running through the engine, and I'm able to call Lua functions from C and C functions from Lua. The way the engine works now, each Object class contains a set of variables that the engine can quickly iterate over to draw or process for physics. While game objects all need to access and manipulate these variables in order for the Game Engine itself to see any changes, they are free to create their own variables, a Lua is exceedingly flexible about this so I don't forsee any issues. Anyway, currently the Game Engine side of things are sitting in C land, and I really want them to stay there for performance reasons. So in an ideal world, when spawning a new game object, I'd need to be able to give Lua read/write access to this standard set of variables as part of the Lua object's base class, which its game logic could then proceed to run wild with. So far, I'm keeping two separate tables of objects in place-- Lua spawns a new game object which adds itself to a numerically indexed global table of objects, and then proceeds to call a C++ function, which creates a new GameObject class and registers the Lua index (an int) with the class. So far so good, C++ functions can now see the Lua object and easily perform operations or call functions in Lua land using dostring. What I need to do now is take the C++ variables, part of the GameObject class, and expose them to Lua, and this is where google is failing me. I've encountered a very nice method here which details the process using tags, but I've read that this method is deprecated in favor of metatables. What is the ideal way to accomplish this? Is it worth the hassle of learning how to pass class definitions around using libBind or some equivalent method, or is there a simple way I can just register each variable (once, at spawn time) with the global lua object? What's the "current" best way to do this, as of Lua 5.1.4?

    Read the article

  • How would I go about sharing variables in a C++ class with Lua?

    - by Nicholas Flynt
    I'm fairly new to Lua, I've been working on trying to implement Lua scripting for logic in a Game Engine I'm putting together. I've had no trouble so far getting Lua up and running through the engine, and I'm able to call Lua functions from C and C functions from Lua. The way the engine works now, each Object class contains a set of variables that the engine can quickly iterate over to draw or process for physics. While game objects all need to access and manipulate these variables in order for the Game Engine itself to see any changes, they are free to create their own variables, a Lua is exceedingly flexible about this so I don't forsee any issues. Anyway, currently the Game Engine side of things are sitting in C land, and I really want them to stay there for performance reasons. So in an ideal world, when spawning a new game object, I'd need to be able to give Lua read/write access to this standard set of variables as part of the Lua object's base class, which its game logic could then proceed to run wild with. So far, I'm keeping two separate tables of objects in place-- Lua spawns a new game object which adds itself to a numerically indexed global table of objects, and then proceeds to call a C++ function, which creates a new GameObject class and registers the Lua index (an int) with the class. So far so good, C++ functions can now see the Lua object and easily perform operations or call functions in Lua land using dostring. What I need to do now is take the C++ variables, part of the GameObject class, and expose them to Lua, and this is where google is failing me. I've encountered a very nice method here which details the process using tags, but I've read that this method is deprecated in favor of metatables. What is the ideal way to accomplish this? Is it worth the hassle of learning how to pass class definitions around using libBind or some equivalent method, or is there a simple way I can just register each variable (once, at spawn time) with the global lua object? What's the "current" best way to do this, as of Lua 5.1.4?

    Read the article

  • StackOverflow Error at java.util.AbstractColllection.<init>(Unknown Source)

    - by thebulge
    I fixed my prior problem yesterday by just separating all the classes into separate files. Nevertheless, I wrote all the code down and seeing no errors was able to compile the program. Or so I thought. Here's the error code: Exception in thread "main" java.lang.StackOverflowError at java.util.AbstractCollection.<init>(Unknown Source) at java.util.AbstractList.<init>(Unknown Source) at java.util.Vector.<init>(Unknown Source) at java.util.Vector.<init>(Unknown Source) at java.util.Vector.<init>(Unknown Source Here are the spots where my I get the errors(marked with problem?) public class GameWorld implements IObservable, IGameWorld { // create collections class public Vector<GameObject> GameObjectList = new Vector<GameObject>(); // PROBLEM private Vector<IObserver> ObserverList = new Vector<IObserver>(); // declare objects Tank pTank = new Tank(10, 10); // other objects and variables to declare public GameWorld() { // add objects to GameObjectList } // accessors/mutators } I get another error here public class Tank extends Movable implements ISteerable { private int armorStrength; private int missileCount; public Tank() {} public Tank(int armStr, int misslCt) // problem? { armorStrength = armStr; // default armorStrength missileCount = misslCt; // default missileCount } public void setDirection(int direction) { this.setDirection(direction); // get input from left turn or right turn // updateValues(); } // access/mutators here I'm stumped on what to do here.

    Read the article

  • Mixing Objective-C and C++: Game Loop Parts

    - by Peteyslatts
    I'm trying to write all of my game in C++ except for drawing and game loop timing. Those parts are going to be in Objective-C for iOS. Right now, I have ViewController handling the update cycle, but I want to create a GameModel class that ViewController could update. I want GameModel to be in C++. I know how to integrate these two classes. My problem is how to have these two parts interact with the drawing and image loading. GameModel will keep track of a list of children of type GameObject. These GameObjects update every frame, and then need to pass position and visibility data to whatever class or method will handle drawing. I feel like I'm answering my own question now (talking it out helps) but would it be a good idea to put all of the visible game objects into an array at the end of the update method, return it, and use that to update graphics inside ViewController?

    Read the article

  • NullReferenceException when accessing variables in a 2D array in Unity

    - by Syed
    I have made a class including variables in Monodevelop which is: public class GridInfo : MonoBehaviour { public float initPosX; public float initPosY; public bool inUse; public int f; public int g; public int h; public GridInfo parent; public int y,x; } Now I am using its class variable in another class, Map.cs which is: public class Map : MonoBehaviour { public static GridInfo[,] Tile = new GridInfo[17, 23]; void Start() { Tile[0,0].initPosX = initPosX; //Line 49 } } I am not getting any error on runtime, but when I play in unity it is giving me error NullReferenceException: Object reference not set to an instance of an object Map.Start () (at Assets/Scripts/Map.cs:49) I am not inserting this script in any gameobject, as Map.cs will make a GridInfo type array, I have also tried using variables using GetComponent, where is the problem ?

    Read the article

  • Entity/Component based engine rendering separation from logic

    - by Denis Narushevich
    I noticed in Unity3D that each gameObject(entity) have its own renderer component, as far I understand, such component handle rendering logic. I wonder if it is a common practice in entity/component based engines, when single entity have renderer components and logic components such as position, behavior altogether in one box? Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside. With such approach it is impossible to swap renderers, it would require to rewrite all that customized renderers. The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities. Is such approach somehow wrong?

    Read the article

  • Python library for scripting (C++ integration)

    - by Edward83
    Please advise me good wrapper/library for python. I need to implement simple scripting in c++ app; Under "good" I mean pretty understandable, well documented, no memory leaking, fast. For creating base interface of GameObject on Python and C++; Your own experience and useful links will be nice!!! I found link about it, but I need more specific within gamedev context. What combinations of libraries you used for python integration into c++? For example about ogre-python it said built using Py++ and Boost.Python library And one more question, maybe someone of you know how Python was integrated into BigWorld engine (it's own port or some library)? Thank you!!!

    Read the article

  • Unity3d: Box collider attached to animated FBX models through scripts at run-time have wrong dimension

    - by Heisenbug
    I have several scripts attached to static and non static models of my scene. All models are instantiated at run-time (and must be instantiated at run-time because I'm procedural building the scene). I'd like to add a BoxCollider or SphereCollider to my FBX models at runtime. With non animated models it works simply requiring BoxCollider component from the script attached to my GameObject. BoxCollider is created of the right dimension. Something like: [RequireComponent(typeof(BoxCollider))] public class AScript: MonoBehavior { } If I do the same thing with animated models, BoxCollider are created of the wrong dimension. For example if attach the script above to penelopeFBX model of the standard asset, BoxCollider is created smaller than the mesh itself. How can I solve this?

    Read the article

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