In my last post http://vackup.blogspot.com.ar/2013/11/unity3d-kill-character-and-make-him-die.html I wrote how kill a character (that uses a rigidbody) and make him die like a ragdoll. The solution was simple, just add him a ragdoll with Unity Ragdoll wizard and set all rigidbodies as Kinematic.
This was working great but all characters don't collide and they pass through other objects. Ouch!!
Searching the internet, I found that "If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore." http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-isKinematic.html
Also I found that someone had the same problem I have "I can't seem to find a specific answer for this. Mainly, I have an enemy rigidbody in my game who, when hit by an attack of some large value, goes ragdoll (isKinematic = false). However, when he is chasing the Player with isKinematic = true, he phases through terrain and such. Is there an elegant way of having an enemy be allowed to go into ragdoll and still collide with the environment?" http://answers.unity3d.com/questions/167712/collisions-with-rigidbodies-with-kinematics.html
And the reply was something I don't want to hear "Actually the only two components that can detect collisions are: the CharacterController and a non-kinematic RigidBody without any exceptions (afaik). However the CharacterController uses it's own detection method and is not really part of the physics system.
The only difference between a simple GameObject with a collider and one with a kinematic Rigidbody attached is that the kinematic Rigidbody can wake up other non-kinematic Rigidbodies. Non-kinematic Rigidbodies fall asleep after a few seconds. They can only detect collisions when they are awake. If you move a GameObject with a sleeping Rigidbody it will wake up automatically, no matter what method of movement you're using (transform.position, AddForce, MovePosition).
The only use of a kinematic Rigidbody is that when you move it into a sleeping Rigidbody it will wake up and would perform the collision check. Keep in mind that the collision messages are sent to both objects but only a non-kinematic Rigidbody can produce them.
I'm not sure how your ragdoll-setup looks like, usually you have multiple body parts that are connected with joints. To move the enemy while he's alive you should use either a CharacterController, or a non kinematic Rigidbody. You should remove it when you turn it into a ragdoll.
If you use a Rigidbody you can set freezeRotation to true so the Rigidbody is not rotated by the physics system but you're still able to rotate the object via script. You can also use Rigidbody.constraints to prevent the rotation and / or position change caused by the physics system."
So I started to think what can I do ... I thought that if isKinematic wasn't my solution, it would be great if I could create the ragdoll at runtime using a script.
So I searched the internet and found someone asking how to "Export ragdoll setup to script" (http://answers.unity3d.com/questions/188917/export-ragdoll-setup-to-script.html). The reply was "I created a code generator for C# and released it as open source under MIT license. Further on I wrote an article in my blog where you can find the code as well". He was talking about C# Code Generator As Add-on for Unity3D Ragdoll Wizard.
There you can find the code to download and how to use it. I use it in my project and the result is what I was trying to achieve. The results are here: http://bit.ly/1beCGTg
Esfuerzo Por Agregar Valor, No Por Ser Perfecto! Strive For Adding Value, Not Being Perfect!
Mostrando las entradas con la etiqueta Fisica. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Fisica. Mostrar todas las entradas
Unity3d: kill a character and make him die like a ragdoll
The other day, I shown a friend of Rosario Game Dev the lastest version of my game where I introduced bombs and explosion. He told me it would be great that when a bomb explodes, characters fly over the scene and that I could achive that by using a ragdoll. You can see a proof of concept here http://bit.ly/17pl47F
So, what's a ragdoll? A ragdoll "is a children's toy. It is a cloth figure, a doll traditionally home-made from (and stuffed with) spare scraps of material" and the same approach is used in video games.
Unity has a simple wizard that lets you quickly create your own ragdoll. You simply have to drag the different limbs on the respective properties in the wizard. Then select create and Unity will automatically generate all Colliders, Rigidbodies and Joints that make up the Ragdoll for you. (something you need to know / guess, as a ragdoll is basically a collection of rigibodies it will be affected by physics, gravity and forces)
Here you have a Unity 3D Ragdoll Easy Tutorial (this all you need to know to make a ragdoll)
This is really easy, but what if the character have any other logic or components like animators, rigidbody, script, etc?
Let's take a look at Ethan from Unity3d Project #01: Stealth. Ethan has a lot of components attached to him.
The result is here http://bit.ly/17pl47F With a mouse click, Ethan dies
You can download the full project here: http://bit.ly/1dYsO1I
So, what's a ragdoll? A ragdoll "is a children's toy. It is a cloth figure, a doll traditionally home-made from (and stuffed with) spare scraps of material" and the same approach is used in video games.
Unity has a simple wizard that lets you quickly create your own ragdoll. You simply have to drag the different limbs on the respective properties in the wizard. Then select create and Unity will automatically generate all Colliders, Rigidbodies and Joints that make up the Ragdoll for you. (something you need to know / guess, as a ragdoll is basically a collection of rigibodies it will be affected by physics, gravity and forces)
Here you have a Unity 3D Ragdoll Easy Tutorial (this all you need to know to make a ragdoll)
This is really easy, but what if the character have any other logic or components like animators, rigidbody, script, etc?
Let's take a look at Ethan from Unity3d Project #01: Stealth. Ethan has a lot of components attached to him.
If I just add the ragdoll to Ethan, It'll be a completly mess (I've already did it, try it by yourself), so what can we do? These are the step I follow (guided by some answers I found on the Internet):
- Create a ragdoll to Ethan
- Disable all child (ragdoll) rigidbodies (script AnimatorToRagdoll.cs)
- When Ethan dies, destroy / disable main components (With a mouse click, Ethan dies)
- Eneable all child (ragdoll) rigidbodies
The result is here http://bit.ly/17pl47F With a mouse click, Ethan dies
You can download the full project here: http://bit.ly/1dYsO1I
Epidemic update, bomb and explosions
Detonator Explosion Framework for Unity makes incorporating good explosions easier for all types of developers. At its most basic level, Detonator is a component that can be attached to any GameObject. At runtime it then creates an explosion with configurable color, size, duration, detail, and sub-elements like sparks, smoke, and shockwaves. The Detonator Parametric Explosion Framework has been developed by Ben Throop for the Unity Summer of Code 2009.
You can play with a running example of Detonator here: http://variancetheory.com/detonator/
You can play with a running example of Detonator here: http://variancetheory.com/detonator/
Just add a component script to my bomb object (eg: a sphere). My script has a public gameobject variable so I can assing the explision prefab I like most.
And only in my script, I just wrote code for OnCollisionEnter:
void OnCollisionEnter(Collision collision) {// Instantiate a detonator game object where the bomb isInstantiate (this.detonator, this.transform.position, Quaternion.identity);// Destroy the bomb (because it exploded lol)Destroy(this.gameObject); }
Remember, you can take a look at the last version of the prototype here http://bit.ly/1beCGTg
Of course, there are a lot of things to improve but I'm just starting
XNA Bezier Curve
A Bézier curve is a type of curve that is easy to use, and can describe many shapes. Bézier curves are famously used for representing characters in fonts, and shapes in vehicle design. Bézier curves are also used in vector art packages for curve drawing, and in 3D animation tools to represent animation paths.
In games, Bézier curves are sometimes useful to describe paths: the racing line in a racing game, or the line in line-drawing games such as Flight Control, or the looping butterfly that enlivens an RPG.
Bézier curves are popular because their mathematical descriptions are compact, intuitive, and elegant. They are easy to compute, easy to use in higher dimensions (3D and up), and can be stitched together to represent any shape you can imagine.
Thanks to http://blog.icode.com/ I can implement a XNA Bezier Curve, here's what it look like.
BezierCurve.cs
using Microsoft.Xna.Framework;
public class BezierCurve
{
public static Vector2 GetPoint(float t, Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
{
float cx = 3 * (p1.X - p0.X);
float cy = 3 * (p1.Y - p0.Y);
float bx = 3 * (p2.X - p1.X) - cx;
float by = 3 * (p2.Y - p1.Y) - cy;
float ax = p3.X - p0.X - cx - bx;
float ay = p3.Y - p0.Y - cy - by;
float Cube = t * t * t;
float Square = t * t;
float resX = (ax * Cube) + (bx * Square) + (cx * t) + p0.X;
float resY = (ay * Cube) + (by * Square) + (cy * t) + p0.Y;
return new Vector2(resX, resY);
}
}
Game.cs (main game loop class)
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2 PlotPoint, p0, p1,p2, p3;
private Texture2D dummyTexture;
private float t;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
///
/// Permite que el juego realice la inicialización que necesite para empezar a ejecutarse.
/// Aquí es donde puede solicitar cualquier servicio que se requiera y cargar todo tipo de contenido
/// no relacionado con los gráficos. Si se llama a base.Initialize, todos los componentes se enumerarán
/// e inicializarán.
///
protected override void Initialize()
{
// TODO: agregue aquí su lógica de inicialización
p0 = new Vector2(75, 250);
p1 = new Vector2(100, 150);
p2 = new Vector2(500, 100);
p3 = new Vector2(550, 200);
base.Initialize();
}
///
/// LoadContent se llama una vez por juego y permite cargar
/// todo el contenido.
///
protected override void LoadContent()
{
// Crea un SpriteBatch nuevo para dibujar texturas.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content para cargar aquí el contenido del juego
this.dummyTexture = new Texture2D(GraphicsDevice, 1, 1);
this.dummyTexture.SetData(new[] { Color.White });
}
///
/// UnloadContent se llama una vez por juego y permite descargar
/// todo el contenido.
///
protected override void UnloadContent()
{
// TODO: descargue aquí todo el contenido que no pertenezca a ContentManager
}
///
/// Permite al juego ejecutar lógica para, por ejemplo, actualizar el mundo,
/// buscar colisiones, recopilar entradas y reproducir audio.
///
/// Proporciona una instantánea de los valores de tiempo.
protected override void Update(GameTime gameTime)
{
// Permite salir del juego
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
var keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.R))
{
t = 0.0f;
}
t += (float)gameTime.ElapsedGameTime.Milliseconds / 1000;
if (t > 1.0f)
{
return;
}
// TODO: agregue aquí su lógica de actualización
//for (float t = 0; t <= 1.0f; t += 0.01f)
//{
PlotPoint = BezierCurve.GetPoint(t, p0, p1, p2, p3);
// now call some function to plot the PlotPoint
// YourDrawFunction(PlotPoint);
//}
base.Update(gameTime);
}
///
/// Se llama cuando el juego debe realizar dibujos por sí mismo.
///
/// Proporciona una instantánea de los valores de tiempo.
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: agregue aquí el código de dibujo
spriteBatch.Begin();
this.spriteBatch.Draw(
this.dummyTexture,
PlotPoint,
new Rectangle(0, 0, 20, 20),
Color.Red);
this.spriteBatch.Draw(
this.dummyTexture,
p0,
new Rectangle(0, 0, 20, 20),
Color.Green);
this.spriteBatch.Draw(
this.dummyTexture,
p1,
new Rectangle(0, 0, 20, 20),
Color.Blue);
this.spriteBatch.Draw(
this.dummyTexture,
p2,
new Rectangle(0, 0, 20, 20),
Color.Yellow);
this.spriteBatch.Draw(
this.dummyTexture,
p3,
new Rectangle(0, 0, 20, 20),
Color.Black);
spriteBatch.End();
base.Draw(gameTime);
}
}
If you want the project source code, just tweet me https://twitter.com/vackup
XNA Projectile Motion
Actualmente me encuentro programando un juego en XNA y tenia que hacer que un personaje lance por el otro a otro personaje.
Buscando en internet me di cuenta que lo que necesitaba hacer era lanzar un proyectil o "Projectile Motion".
La verdad me senti medio decepcionado porque no encontre un ejemplo sencillo sobre esto asi que gracias a un par de formulas y ejemplos, pude hacer lo que queria y lo comparto con ustedes... devuelvo a la comunidad un poquito de lo que ella me dio. Espero que les sirva!!!
Aca les dejo un video en el cual me base:
Buscando en internet me di cuenta que lo que necesitaba hacer era lanzar un proyectil o "Projectile Motion".
La verdad me senti medio decepcionado porque no encontre un ejemplo sencillo sobre esto asi que gracias a un par de formulas y ejemplos, pude hacer lo que queria y lo comparto con ustedes... devuelvo a la comunidad un poquito de lo que ella me dio. Espero que les sirva!!!
Aca les dejo un video en el cual me base:
Las fuentes que consulte y me sirvieron fueron:
- Projectile motion in Physics: http://www.staff.amu.edu.pl/~romangoc/M2-1-projectile-motion.html
- XNA and C# - Projectile Motion - Tutorial and Download: http://www.youtube.com/watch?v=MSzZd8TLOK4
- Animate Sprite Along a Curve path in XNA: http://stackoverflow.com/questions/3273396/animate-sprite-along-a-curve-path-in-xna (donde responde Andrew Russell - http://andrewrussell.net/ el desarrollador detras del proyecto ExEN - XNA multiplataforma)
Download (XNA 4.0 - VS2010):
Suscribirse a:
Entradas (Atom)
