Search Results

Search found 51 results on 3 pages for 'collider'.

Page 1/3 | 1 2 3  | Next Page >

  • Hadron Collider – Can it unveil the hidden secrets of universe?

    - by samsudeen
    Scientist at  European Centre for Nuclear Research (CERN) today successfully simulated the Big Bang experiment finally by producing  the world’s first high-energy particle collision.This is achieved through the collision of two protons with a total energy of  around seven trillion electron volts sending sub-particles spread through in every direction.   The experiment is conducted successfully around the  European Centre for Nuclear Research (CERN) which is under 100 metres below the Franco-Swiss border. This is said to be the biggest experiment in terms on the investment (around $7 billion) and the scientific importance. This will lead to a new era of science and could change the theories about the origin of universe. You can find  more videos about the experiment at the LHC Videos Join us on Facebook to read all our stories right inside your Facebook news feed.

    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

  • 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

  • Mass Ball-to-Ball Collision Handling (as in, lots of balls)

    - by BlueThen
    Update: Found out that I was using the radius as the diameter, which was why the mtd was overcompensating. Hi, StackOverflow. I've written a Processing program awhile back simulating ball physics. Basically, I have a large number of balls (1000), with gravity turned on. Detection works great, but my issue is that they start acting weird when they're bouncing against other balls in all directions. I'm pretty confident this involves the handling. For the most part, I'm using Jay Conrod's code. One part that's different is if (distance > 1.0) return; which I've changed to if (distance < 1.0) return; because the collision wasn't even being performed with the first bit of code, I'm guessing that's a typo. The balls overlap when I use his code, which isn't what I was looking for. My attempt to fix it was to move the balls to the edge of each other: float angle = atan2(y - collider.y, x - collider.x); float distance = dist(x,y, balls[ID2].x,balls[ID2].y); x = collider.x + radius * cos(angle); y = collider.y + radius * sin(angle); This isn't correct, I'm pretty sure of that. I tried the correction algorithm in the previous ball-to-ball topic: // get the mtd Vector2d delta = (position.subtract(ball.position)); float d = delta.getLength(); // minimum translation distance to push balls apart after intersecting Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / ball.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2))); except my version doesn't use vectors, and every ball's weight is 1. The resulting code I get is this: PVector delta = new PVector(collider.x - x, collider.y - y); float d = delta.mag(); PVector mtd = new PVector(delta.x * ((radius + collider.radius - d) / d), delta.y * ((radius + collider.radius - d) / d)); // push-pull apart based on mass x -= mtd.x * 0.5; y -= mtd.y * 0.5; collider.x += mtd.x * 0.5; collider.y += mtd.y * 0.5; This code seems to over-correct collisions. Which doesn't make sense to me because in no other way do I modify the x and y values of each ball, other than this. Some other part of my code could be wrong, but I don't know. Here's the snippet of the entire ball-to-ball collision handling I'm using: if (alreadyCollided.contains(new Integer(ID2))) // if the ball has already collided with this, then we don't need to reperform the collision algorithm return; Ball collider = (Ball) objects.get(ID2); PVector collision = new PVector(x - collider.x, y - collider.y); float distance = collision.mag(); if (distance == 0) { collision = new PVector(1,0); distance = 1; } if (distance < 1) return; PVector velocity = new PVector(vx,vy); PVector velocity2 = new PVector(collider.vx, collider.vy); collision.div(distance); // normalize the distance float aci = velocity.dot(collision); float bci = velocity2.dot(collision); float acf = bci; float bcf = aci; vx += (acf - aci) * collision.x; vy += (acf - aci) * collision.y; collider.vx += (bcf - bci) * collision.x; collider.vy += (bcf - bci) * collision.y; alreadyCollided.add(new Integer(ID2)); collider.alreadyCollided.add(new Integer(ID)); PVector delta = new PVector(collider.x - x, collider.y - y); float d = delta.mag(); PVector mtd = new PVector(delta.x * ((radius + collider.radius - d) / d), delta.y * ((radius + collider.radius - d) / d)); // push-pull apart based on mass x -= mtd.x * 0.2; y -= mtd.y * 0.2; collider.x += mtd.x * 0.2; collider.y += mtd.y * 0.2; Thanks. (Apologies for lack of sources, stackoverflow thinks I'm a spammer)

    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

  • How to make an object move again after being stopped by collision in Unity?

    - by Matthew Underwood
    I have a player object which position is always centered on the main camera's viewport. This object has a Rigidbody 2D, a box and circle collider. The player moves around a level, the level has a polygon collider attached. I move the camera until the object hits against the collider, which stops the movement of the camera by setting its speed to 0. The problem happens when I want to move the camera / player object away from the collider. As the speed is already at 0, it cannot move away from the collider. The script attached to the player object, checks for collisions and applies the speed to 0 on the main camera's test script. using UnityEngine; using System.Collections; public class move : MonoBehaviour { public float speed; public test testing; // Use this for initialization void Start () { speed = 10F; testing = Camera.main.GetComponent<test>(); } // Update is called once per frame void FixedUpdate () { Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane)); transform.position = new Vector3(p.x, p.y, -1); } void OnCollisionEnter2D(Collision2D col) { testing.speed = 0; } void OnCollisionExit2D(Collision2D col) { testing.speed = 10F; } } This is the script attached to the main camera; just a simple script that changes the camera's position. using UnityEngine; using System.Collections; public class test : MonoBehaviour { public float speed; public float translationY; public float translationX; // Use this for initialization void Start () { speed = 10F; } void FixedUpdate () { translationY = Input.GetAxis("Vertical") * speed * Time.deltaTime; translationX = Input.GetAxis("Horizontal") * speed * Time.deltaTime; transform.Translate(translationX, translationY, 0); } } The player object isn't kinematic and is a fixed angle, the colliders aren't triggers and the polygon collider isn't a trigger either. The player is the red square, the collider is the pink area. -- EDIT -- From the latest change the collider set up for the player So if the X speed was disabled. It wouldnt move into the side of the polygon colider which is good, but yet you couldnt move away from it. And moving down would move inside the colider.

    Read the article

  • Periodic updates of an object in Unity

    - by Blue
    I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error: Update() cannot be a coroutine.) How would I fix this? Would I need a timer system to toggle the collider? var waitTime : float = 1; var trigger : boolean = false; function Update () { if(!trigger){ collider.enabled = false; yield WaitForSeconds(waitTime); } if(trigger){ collider.enabled = true; yield WaitForSeconds(waitTime); } } }

    Read the article

  • Enabling and Disabling Colliders Unity

    - by Blue
    I'm trying to make the collider appear every 1 second. But I can't get the code write. I tried enabling the collider under a boolean and putting a yield to make it every second or so. But it's not working(gives me an error: Update() can not be a coroutine.). How would I fix this? Would I need a timer system and set the collider to be enabled every 'x' seconds and disabled every 'y' seconds? var waitTime : float = 1; var trigger : boolean = false; function Update () { if(!trigger){ collider.enabled = false; yield WaitForSeconds(waitTime); } if(trigger){ collider.enabled = true; yield WaitForSeconds(waitTime); } } }

    Read the article

  • Enabling and Disabling components in Unity

    - by Blue
    I'm trying to create an enable/ disable game objects in Unity. I used GameObject.SetActiveRecursively but it only works one-way. I used a collider in which when an object enters the collider. The game objects become enabled. When they leave or get to a certain point, they disable. How would I make this a two way system, making it able to be enabled while inside the collider and disabled when outside the collider? -- The collider is in the game object who is being disabled and enabled. According to this information from Unity Answers, the object becomes disabled. So how would I make the object enabled?

    Read the article

  • How do I add a Rigid body and a box collider component to a Texture2D?

    - by gamenewdev
    I am making a snake game. I'm basing it on a basic tutorial game, which does no collision detection, wall checking or different levels. All snake head, piece, food, even the background is made of Texture2D. I want the head of the snake to detects 2D collisions with them, but Rect.contains isn't working. I'd prefer to detect collisions by onTriggerEnter() for which I need to add BoxCollider to my snakeHead.

    Read the article

  • OnTrigger not firing consistently

    - by Lautaro
    I have a Prefab called Player which has a Body and a Sword. The game uses 2 instances of Player, Player1 and Player2. I use Player1 to strike Player2. This is code on the sword. My hope is that Sword of Player1 will log on contct with Body of Player2. It happens but only the first hit and then i have to hit several times before another strike is logged. But when i look at log from OnTriggerStay it looks like the TriggerExit is never detected untill long after the sword is gone. void OnTriggerEnter(Collider other) { //Play sound to confirm collision var sm = ObjectDirectory.soundManager; sm.PlaySoundClip(sm.gui_02); Debug.Log(other.name + " - ENTER" ); } void OnTriggerStay(Collider other) { Debug.Log(other.name + " - collision" ); } void OnTriggerExit(Collider other) { Debug.Log(other.name + " - HAS LEFT" ); } DEBUG LOG: Player2 - ENTER UnityEngine.Debug:Log(Object) SwordControl:OnTriggerEnter(Collider) (at Assets/Scripts/SwordControl.cs:28) Player2 - collision UnityEngine.Debug:Log(Object) SwordControl:OnTriggerStay(Collider) (at Assets/Scripts/SwordControl.cs:34) (The last debug log then repeated hundreds of times long after the sword of player 1 had withdrawn and was in no contact with player 2 ) EDIT: Further tests shows that if i move player1 backwards away form player2 i trigger the OnTriggerExit. Even if the sword is not touching Player2 since after the blow. However even after OnTriggerExit it takes many tries untill i can get another blow registered.

    Read the article

  • Would it be more efficient to handle 2D collision detection with polygons, rather than both squares/polygons?

    - by KleptoKat
    I'm working on a 2D game engine and I'm trying to get collision detection as efficient as possible. One thing I've noted is that I have a Rectangle Collision collider, a Shape (polygon) collider and a circle collider. Would it be more efficient (either dev-time wise or runtime wise) to have just one shape collider, rather than have that and everything else? I feel it would optimize my code in the back end, but how much would it affect my game at runtime? Should I be concerned with this at all, as 3D games generally have tens of thousands of polygons?

    Read the article

  • Unity Problem with colliding instances of same object

    - by Kuba Sienkiewicz
    I want to check if object's instance is overlapping with another instance (any spawned object with another spawned object, not necessary the same object). I'm doing this by detecting collisions between bodies. But I have a problem. Spawned object (instances) are detecting collision with everything but other spawned objects. I've checked collision layers etc. All of spawned objects have rigidbodies and mesh colliders. Also when I attach my script to another body and I touch that body with an instanced object it detects collision. So problem is visible only in collision between spawned objects. And one more information I have script, rigid body and collider attached to child of main object. using UnityEngine; using System.Collections; public class CantPlace : MonoBehaviour { public bool collided = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //Debug.Log (collided); } void OnTriggerEnter(Collider collider) { //if (true) { //foreach (Transform child in this.transform) { // if (child.name == "Cylinder") { //collided = true; Color c; c = this.renderer.material.color; c.g = 0f; c.b = 1f; c.r = 0f; this.renderer.material.color = c; Debug.Log (collider.name); //} // } //} //foreach (ContactPoint contact in collision.contacts) { // Debug.DrawRay(contact.point, contact.normal, Color.red,15f); // } } }

    Read the article

  • Why doesn't Unity's OnCollisionEnter give me surface normals, and what's the most reliable way to get them?

    - by michael.bartnett
    Unity's on collision event gives you a Collision object that gives you some information about the collision that happened (including a list of ContactPoints with hit normals). But what you don't get is surface normals for the collider that you hit. Here's a screenshot to illustrate. The red line is from ContactPoint.normal and the blue line is from RaycastHit.normal. Is this an instance of Unity hiding information to provide a simplified API? Or do standard 3D realtime collision detection techniques just not collect this information? And for the second part of the question, what's a surefire and relatively efficient way to get a surface normal for a collision? I know that raycasting gives you surface normals, but it seems I need to do several raycasts to accomplish this for all scenarios (maybe a contact point/normal combination misses the collider on the first cast, or maybe you need to do some average of all the contact points' normals to get the best result). My current method: Back up the Collision.contacts[0].point along its hit normal Raycast down the negated hit normal for float.MaxValue, on Collision.collider If that fails, repeat steps 1 and 2 with the non-negated normal If that fails, try steps 1 to 3 with Collision.contacts[1] Repeat 4 until successful or until all contact points exhausted. Give up, return Vector3.zero. This seems to catch everything, but all those raycasts make me queasy, and I'm not sure how to test that this works for enough cases. Is there a better way?

    Read the article

  • 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

  • Unity AddExplosionForce not doing anything

    - by Zero
    Recently I've started learning Unity3D. I'm working on a game as an exercise in which you control a space ship and have to dodge asteroids. If you feel like it's getting a bit too much you can hit the space bar, emitting a blast in all directions that repulses nearby asteroids. To create this blast I have the following code: public class PlayerBlastScript : MonoBehaviour { public ParticleSystem BlastEffect; // Update is called once per frame void Update () { if (Input.GetKeyUp(KeyCode.Space)) { Fire(); } } public void Fire() { ParticleEmitter effect = (ParticleEmitter) Instantiate (BlastEffect, transform.position, Quaternion.identity); effect.Emit(); Vector3 explosionPos = transform.position; Collider[] colliders = Physics.OverlapSphere(explosionPos, 25.0f); foreach(Collider hit in colliders) { if (!hit) { continue; } if (hit.rigidbody) { hit.rigidbody.AddExplosionForce(5000.0f, explosionPos, 100.0f); } } } } Even though the blast effect appears, the asteroids are not affected at all. The asteroids are all rigid bodies so what's the problem?

    Read the article

  • 3D/perspective Top down shooter bullet issues

    - by Tseng
    I'm developing a top-down shooter with multiple levels (ground for ground units, middle level for buildings, top level for air unity). The problem is the collision. Though I can make the collider box of a bullet be long enough to reach the ground (and collide with it), the real issue is optical. When the bullet is fired from a aircraft and collides with some object on the ground (building, ground unit) it will be optically offset due to the perspective camera, because it looks like the shot "by-passed" the target as seen below Is there any way to make the bullets collide perspectively correct? I'm using Unity3d Engine and it offers only simple colliders (box, sphere, cylinder, mesh and wheel), though I don't think a cone-formed collider would solve this issue. I'd need a (cheap) way to check if it's overlapping a destructible object? I thought of casting a ray from the camera through the bullet and if it hits something destructible, trigger an action, but that's quite punctual and maybe to performance heavy on certain number of bullets

    Read the article

  • Repelling a rigidbody in the direction an object is rotating

    - by ndg
    Working in Unity, I have a game object which I rotate each frame, like so: void Update() { transform.Rotate(new Vector3(0, 1, 0) * speed * Time.deltaTime); } However, I'm running into problems when it comes to applying a force to rigidbodies that collide with this game objects sphere collider. The effect I'm hoping to achieve is that objects which touch the collider are thrown in roughly the same direction as the object is rotating. To do this, I've tried the following: Vector3 force = ((transform.localRotation * Vector3.forward) * 2000) * Time.deltaTime; collision.gameObject.rigidbody.AddForce(force, ForceMode.Impulse); Unfortunately this doesn't always match the rotation of the object. To debug the issue, I wrote a simple OnDrawGizmos script, which (strangely) appears to draw the line correctly oriented to the rotation. void OnDrawGizmos() { Vector3 pos = transform.position + ((transform.localRotation * Vector3.forward) * 2); Debug.DrawLine(transform.position, pos, Color.red); } You can see the result of the OnDrawGizmos function below: What am I doing wrong?

    Read the article

  • Convert mht\pdf\excel and encoding

    - by CoLLiDeR
    I am looking for a .net library that can help me do one of the following: 1. Convert an MHT file to PDF 2. Convert between pdf versions 3. Change a pdf file encoding 4. Convert an MHT to an Excel file 5. Convert a MIME version of excel (an Excel file that is readable via notepad) to a binary Excel file 6. Convert between Excel version

    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

  • Executing Components in an Entity Component System

    - by John
    Ok so I am just starting to grasp the whole ECS paradigm right now and I need clarification on a few things. For the record, I am trying to develop a game using C++ and OpenGL and I'm relatively new to game programming. First of all, lets say I have an Entity class which may have several components such as a MeshRenderer,Collider etc. From what I have read, I understand that each "system" carries out a specific task such as calculating physics and rendering and may use more that one component if needed. So for example, I would have a MeshRendererSystem act on all entities with a MeshRenderer component. Looking at Unity, I see that each Gameobject has, by default, got components such as a renderer, camera, collider and rigidbody etc. From what I understand, an entity should start out as an empty "container" and should be filled with components to create a certain type of game object. So what I dont understand is how the "system" works in an entity component system. http://docs.unity3d.com/ScriptReference/GameObject.html So I have a GameObject(The Entity) class like class GameObject { public: GameObject(std::string objectName); ~GameObject(void); Component AddComponent(std::string name); Component AddComponent(Component componentType); }; So if I had a GameObject to model a warship and I wanted to add a MeshRenderer component, I would do the following: warship->AddComponent(new MeshRenderer()); In the MeshRenderers constructor, should I call on the MeshRendererSystem and "subscribe" the warship object to this system? In that case, the MeshRendererSystem should probably be a Singleton("shudder"). From looking at unity's GameObject, if each object potentially has a renderer or any of the components in the default GameObject class, then Unity would iterate over all objects available. To me, this seems kind of unnecessary since some objects might not need to be rendered for example. How, in practice, should these systems be implemented?

    Read the article

  • How can I resolve component types in a way that supports adding new types relatively easily?

    - by John
    I am trying to build an Entity Component System for an interactive application developed using C++ and OpenGL. My question is quite simple. In my GameObject class I have a collection of Components. I can add and retrieve components. class GameObject: public Object { public: GameObject(std::string objectName); ~GameObject(void); Component * AddComponent(std::string name); Component * AddComponent(Component componentType); Component * GetComponent (std::string TypeName); Component * GetComponent (<Component Type Here>); private: std::map<std::string,Component*> m_components; }; I will have a collection of components that inherit from the base Components class. So if I have a meshRenderer component and would like to do the following GameObject * warship = new GameObject("myLovelyWarship"); MeshRenderer * meshRenderer = warship->AddComponent(MeshRenderer); or possibly MeshRenderer * meshRenderer = warship->AddComponent("MeshRenderer"); I could be make a Component Factory like this: class ComponentFactory { public: static Component * CreateComponent(const std::string &compTyp) { if(compTyp == "MeshRenderer") return new MeshRenderer; if(compTyp == "Collider") return new Collider; return NULL; } }; However, I feel like I should not have to keep updating the Component Factory every time I want to create a new custom Component but it is an option. Is there a more proper way to add and retrieve these components? Is standard templates another solution?

    Read the article

  • How could I implement 3D player collision with rotation in LWJGL?

    - by Tinfoilboy
    I have a problem with my current collision implementation. Currently for player collision, I just use an AABB where I check if another AABB is in the way of the player, as shown in this code. (The code below is a sample of checking for collisions in the Z axis) for (int z = (int) (this.position.getZ()); z > this.position.getZ() - moveSpeed - boundingBoxDepth; z--) { // The maximum Z you can get. int maxZ = (int) (this.position.getZ() - moveSpeed - boundingBoxDepth) + 1; AxisAlignedBoundingBox aabb = WarmupWeekend.getInstance().currentLevel.getAxisAlignedBoundingBoxAt(new Vector3f(this.position.getX(), this.position.getY(), z)); AxisAlignedBoundingBox potentialCameraBB = new AxisAlignedBoundingBox(this, "collider", new Vector3f(this.position.getX(), this.position.getY(), z), boundingBoxWidth, boundingBoxHeight, boundingBoxDepth); if (aabb != null) { if (potentialCameraBB.colliding(aabb) && aabb.COLLIDER_TYPE.equalsIgnoreCase("collider")) { break; } else if (!potentialCameraBB.colliding(aabb) && z == maxZ) { if (this.grounded) { playFootstep(); } this.position.z -= moveSpeed; break; } } else if (z == maxZ) { if (this.grounded) { playFootstep(); } this.position.z -= moveSpeed; break; } } Now, when I tried to implement rotation to this method, everything broke. I'm wondering how I could implement rotation to this block (and as all other checks in each axis are the same) and others. Thanks in advance.

    Read the article

  • C# XNA Handle mouse events?

    - by user406470
    I'm making a 2D game engine called Clixel over on GitHub. The problem I have relates to two classes, ClxMouse and ClxButton. In it I have a mouse class - the code for that can be viewed here. ClxMouse using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace org.clixel { public class ClxMouse : ClxSprite { private MouseState _curmouse, _lastmouse; public int Sensitivity = 3; public bool Lock = true; public Vector2 Change { get { return new Vector2(_curmouse.X - _lastmouse.X, _curmouse.Y - _lastmouse.Y); } } private int _scrollwheel; public int ScrollWheel { get { return _scrollwheel; } } public bool LeftDown { get { if (_curmouse.LeftButton == ButtonState.Pressed) return true; else return false; } } public bool RightDown { get { if (_curmouse.RightButton == ButtonState.Pressed) return true; else return false; } } public bool MiddleDown { get { if (_curmouse.MiddleButton == ButtonState.Pressed) return true; else return false; } } public bool LeftPressed { get { if (_curmouse.LeftButton == ButtonState.Pressed && _lastmouse.LeftButton == ButtonState.Released) return true; else return false; } } public bool RightPressed { get { if (_curmouse.RightButton == ButtonState.Pressed && _lastmouse.RightButton == ButtonState.Released) return true; else return false; } } public bool MiddlePressed { get { if (_curmouse.MiddleButton == ButtonState.Pressed && _lastmouse.MiddleButton == ButtonState.Released) return true; else return false; } } public bool LeftReleased { get { if (_curmouse.LeftButton == ButtonState.Released && _lastmouse.LeftButton == ButtonState.Pressed) return true; else return false; } } public bool RightReleased { get { if (_curmouse.RightButton == ButtonState.Released && _lastmouse.RightButton == ButtonState.Pressed) return true; else return false; } } public bool MiddleReleased { get { if (_curmouse.MiddleButton == ButtonState.Released && _lastmouse.MiddleButton == ButtonState.Pressed) return true; else return false; } } public MouseState CurMouse { get { return _curmouse; } } public MouseState LastMouse { get { return _lastmouse; } } public ClxMouse() : base(ClxG.Textures.Default.Cursor) { _curmouse = Mouse.GetState(); _lastmouse = _curmouse; CollisionBox = new Rectangle(ClxG.Screen.Center.X, ClxG.Screen.Center.Y, Texture.Width, Texture.Height); this.Solid = false; DefaultPosition = new Vector2(CollisionBox.X, CollisionBox.Y); Mouse.SetPosition(CollisionBox.X, CollisionBox.Y); } public ClxMouse(Texture2D _texture) : base(_texture) { _curmouse = Mouse.GetState(); _lastmouse = _curmouse; CollisionBox = new Rectangle(ClxG.Screen.Center.X, ClxG.Screen.Center.Y, Texture.Width, Texture.Height); DefaultPosition = new Vector2(CollisionBox.X, CollisionBox.Y); } public override void Update() { _lastmouse = _curmouse; _curmouse = Mouse.GetState(); if (_curmouse != _lastmouse) { if (ClxG.Game.IsActive) { _scrollwheel = _curmouse.ScrollWheelValue; Velocity = new Vector2(Change.X / Sensitivity, Change.Y / Sensitivity); if (Lock) Mouse.SetPosition(ClxG.Screen.Center.X, ClxG.Screen.Center.Y); _curmouse = Mouse.GetState(); } base.Update(); } } public override void Draw(SpriteBatch _sb) { base.Draw(_sb); } } } ClxButton using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace org.clixel { public class ClxButton : ClxSprite { /// <summary> /// The color when the mouse is over the button /// </summary> public Color HoverColor; /// <summary> /// The color when the color is being clicked /// </summary> public Color ClickColor; /// <summary> /// The color when the button is inactive /// </summary> public Color InactiveColor; /// <summary> /// The color when the button is active /// </summary> public Color ActiveColor; /// <summary> /// The color after the button has been clicked. /// </summary> public Color ClickedColor; /// <summary> /// The text to be displayed on the button, set to "" if no text is needed. /// </summary> public string Text; /// <summary> /// The ClxText object to be displayed. /// </summary> public ClxText TextRender; /// <summary> /// The ClxState that should be ResetAndShow() when the button is clicked. /// </summary> public ClxState ClickState; /// <summary> /// Collision check to make sure onCollide() only runs once per frame, /// since only the mouse needs to be collision checked. /// </summary> private bool _runonce = false; /// <summary> /// Gets a value indicating whether this instance is colliding. /// </summary> /// <value> /// <c>true</c> if this instance is colliding; otherwise, <c>false</c>. /// </value> public bool IsColliding { get { return _runonce; } } /// <summary> /// Initializes a new instance of the <see cref="ClxButton"/> class. /// </summary> public ClxButton() : base(ClxG.Textures.Default.Button) { HoverColor = Color.Red; ClickColor = Color.Blue; InactiveColor = Color.Gray; ActiveColor = Color.White; ClickedColor = Color.Yellow; Text = Name + ID + " Unset!"; TextRender = new ClxText(); TextRender.Text = Text; TextRender.TextPadding = new Vector2(5, 5); ClickState = null; CollideObjects(ClxG.Mouse); } /// <summary> /// Initializes a new instance of the <see cref="ClxButton"/> class. /// </summary> /// <param name="_texture">The button texture.</param> public ClxButton(Texture2D _texture) : base(_texture) { HoverColor = Color.Red; ClickColor = Color.Blue; InactiveColor = Color.Gray; ActiveColor = Color.White; ClickedColor = Color.Yellow; Texture = _texture; Text = Name + ID; TextRender = new ClxText(); TextRender.Name = this.Name + ".TextRender"; TextRender.Text = Text; TextRender.TextPadding = new Vector2(5, 5); TextRender.Reset(); ClickState = null; CollideObjects(ClxG.Mouse); } /// <summary> /// Draws the debug information, run from ClxG.DrawDebug unless manual control is assumed. /// </summary> /// <param name="_sb">SpriteBatch used for drawing.</param> public override void DrawDebug(SpriteBatch _sb) { _runonce = false; TextRender.DrawDebug(_sb); _sb.Draw(Texture, ActualRectangle, new Rectangle(0, 0, Texture.Width, Texture.Height), DebugColor, Rotation, Origin, Flip, Layer); _sb.Draw(ClxG.Textures.Default.DebugBG, new Rectangle(ActualRectangle.X - DebugLineWidth, ActualRectangle.Y - DebugLineWidth, ActualRectangle.Width + DebugLineWidth * 2, ActualRectangle.Height + DebugLineWidth * 2), new Rectangle(0, 0, ClxG.Textures.Default.DebugBG.Width, ClxG.Textures.Default.DebugBG.Height), DebugOutline, Rotation, Origin, Flip, Layer - 0.1f); _sb.Draw(ClxG.Textures.Default.DebugBG, ActualRectangle, new Rectangle(0, 0, ClxG.Textures.Default.DebugBG.Width, ClxG.Textures.Default.DebugBG.Height), DebugBGColor, Rotation, Origin, Flip, Layer - 0.01f); } /// <summary> /// Draws using the SpriteBatch, run from ClxG.Draw unless manual control is assumed. /// </summary> /// <param name="_sb">SpriteBatch used for drawing.</param> public override void Draw(SpriteBatch _sb) { _runonce = false; TextRender.Draw(_sb); if (Visible) if (Debug) { DrawDebug(_sb); } else _sb.Draw(Texture, ActualRectangle, new Rectangle(0, 0, Texture.Width, Texture.Height), Color, Rotation, Origin, Flip, Layer); } /// <summary> /// Updates this instance. /// </summary> public override void Update() { if (this.Color != ActiveColor) this.Color = ActiveColor; TextRender.Layer = this.Layer + 0.03f; TextRender.Text = Text; TextRender.Scale = .5f; TextRender.Name = this.Name + ".TextRender"; TextRender.Origin = new Vector2(TextRender.CollisionBox.Center.X, TextRender.CollisionBox.Center.Y); TextRender.Center(this); TextRender.Update(); this.CollisionBox.Width = (int)(TextRender.CollisionBox.Width * TextRender.Scale) + (int)(TextRender.TextPadding.X * 2); this.CollisionBox.Height = (int)(TextRender.CollisionBox.Height * TextRender.Scale) + (int)(TextRender.TextPadding.Y * 2); base.Update(); } /// <summary> /// Collide event, takes the colliding object to call it's proper collision code. /// You'd want to use something like if(typeof(collider) == typeof(ClxObject) /// </summary> /// <param name="collider">The colliding object.</param> public override void onCollide(ClxObject collider) { if (!_runonce) { _runonce = true; UpdateEvents(); base.onCollide(collider); } } /// <summary> /// Updates the mouse based events. /// </summary> public void UpdateEvents() { onHover(); if (ClxG.Mouse.LeftReleased) { onLeftReleased(); return; } if (ClxG.Mouse.RightReleased) { onRightReleased(); return; } if (ClxG.Mouse.MiddleReleased) { onMiddleReleased(); return; } if (ClxG.Mouse.LeftPressed) { onLeftClicked(); return; } if (ClxG.Mouse.RightPressed) { onRightClicked(); return; } if (ClxG.Mouse.MiddlePressed) { onMiddleClicked(); return; } if (ClxG.Mouse.LeftDown) { onLeftClick(); return; } if (ClxG.Mouse.RightDown) { onRightClick(); return; } if (ClxG.Mouse.MiddleDown) { onMiddleClick(); return; } } /// <summary> /// Shows the state of the click. /// </summary> public void ShowClickState() { if (ClickState != null) { ClickState.ResetAndShow(); } } /// <summary> /// Hover event /// </summary> virtual public void onHover() { this.Color = HoverColor; } /// <summary> /// Left click event /// </summary> virtual public void onLeftClick() { this.Color = ClickColor; } /// <summary> /// Right click event /// </summary> virtual public void onRightClick() { } /// <summary> /// Middle click event /// </summary> virtual public void onMiddleClick() { } /// <summary> /// Left click event, called once per click /// </summary> virtual public void onLeftClicked() { ShowClickState(); } /// <summary> /// Right click event, called once per click /// </summary> virtual public void onRightClicked() { this.Reset(); } /// <summary> /// Middle click event, called once per click /// </summary> virtual public void onMiddleClicked() { } /// <summary> /// Ons the left released. /// </summary> virtual public void onLeftReleased() { this.Color = ClickedColor; } virtual public void onRightReleased() { } virtual public void onMiddleReleased() { } } } The issue I have is that I have all these have event styled methods, especially in ClxButton with all the onLeftClick, onRightClick, etc, etc. Is there a better way for me to handle these events to be a lot more easier for a programmer to use? I was looking at normal events on some other sites, (I'd post them but I need more rep.) and didn't really see a good way to implement delegate events into my framework. I'm not really sure how these events work, could someone possibly lay out how these events are processed for me? TL:DR * Is there a better way to handle events like this? * Are events a viable solution to this problem? Thanks in advance for any help.

    Read the article

1 2 3  | Next Page >