I am trying to implement the physics of a canon-ball (a little cumbersome code and that is fine and I don't really need to change it as I am learning).
I think I have done physics numerical method correctly but the problem is that my computer adds the numbers wrong, and it gives me terrible results.
![alt text][1]
[1]: /storage/temp/79374-c9c2525bc06551417d58a1e37971240f.png
Just take a look at this specific variable in one example of a loop in a "for" loop. I print out the loop number, do calculations and then print out the variables.
That means that for this calculation I need to use the previous vy. The top vy is 22.47091.
As you can see at the bottom which I have highlighted the C is: -0.0009003537
This is a code snippet:
float c = (a2y * dt * 0.5f);
float v3y = (vy + c);
V3y according to Unity becomes 22.69472 but that cannot be correct because 22.47091+(-0.0009003537) = 22.46190646
The loop:
for (int i = 0; i < 1000; i++) {
Debug.Log(i);
RungakuttaX(vx, sx, vy, sy, dt);
gameObject.transform.position = new Vector3(sx, sy, 0);
}
The rest of the code:
private void RungakuttaX(float vx, float sx, float vy, float sy, float dt) {
float v1x = vx;
float s1x = sx;
float v1y = vy;
float s1y = sy;
float a1x = FormelX(v1x, v1y);
float a1y = FormelY(v1x, v1y);
float v2x = (vx + (a1x * dt * 0.5f));
float s2x = (sx + (v1x * dt * 0.5f));
float v2y = (vy + (a1y * dt * 0.5f));
float s2y = (sy + (v1y * dt * 0.5f));
float a2x = FormelX(v2x, v2y);
float a2y = FormelY(v2x, v2y);
float v3x = (vx + (a2x * dt * 0.5f));
float s3x = (sx + (v2x * dt * 0.5f));
float c = (a2y * dt * 0.5f);
float v3y = (vy + c);
float s3y = (sy + (v2y * dt * 0.5f));
float a3x = FormelX(v3x, v3y);
float a3y = FormelY(v3x, v3y);
float v4x = (vx + (a3x * dt));
float s4x = (sx + (v3x * dt));
float v4y = (vy + (a3y * dt));
float s4y = (sy + (v3y * dt));
float a4x = FormelX(v4x, v4y);
float a4y = FormelY(v4x, v4y);
this.vx = vx + ((dt/6) * (v1x + 2*v2x + 2*v3x + v4x));
this.sx = sx + ((dt/6) * (s1x + 2*s2x + 2*s3x + s4x));
this.vy = vy + ((dt/6) * (v1y + 2*v2y + 2*v3y + v4y));
this.sy = sy + ((dt/6) * (s1y + 2*s2y + 2*s3y + s4y));
Debug.Log("vy:"+vy+" v1y:" + v1y + " a1y:" + a1y + " v2y:" + v2y + " a2y:" + a2y + " c:" + c +" v3y:" + v3y + " a3y:" + a3y + " v4y" + v4y + " a4y" + a4y + "---");
}
public float FormelX(float vx, float vy) {
float v = Mathf.Sqrt((vx * vx) + (vy * vy));
float d = (0.5f * p * (v * v) * c * a)/m;
float dx = -d * (vx / v);
if (v != 0)
{
return dx;
}
else
{
return 0;
}
}
public float FormelY(float vx, float vy) {
float v = Mathf.Sqrt((vx * vx) + (vy * vy));
float d = (0.5f * p * (v * v) * c * a)/m + g;
float dy = -d * (vy / v);
if (v != 0)
{
return dy;
}
else
{
return 0;
}
}
↧
My computer does not know how to add I think
↧
OnTriggerStay2D do not called every fixedUpdate
i am using unity 5.4.2f2 Personal, and i think 5.3 has the same issue.
OnTriggerStay2D do not called every fixedUpdate.
to reproduce, do like below:
(1) two gameObject objA and objB, both with a trigger2D.
(2) put objA and objB close enough so their triggers are overlapped.
(3) add below script to objA:
public class objAControl : MonoBehaviour {
void OnTriggerStay2D(Collider2D coll){
Debug.Log("----OnTriggerStay2D");
}
void FixedUpdate(){
Debug.Log("----FixedUpdate");
}
}
(4) run the scene and see log.
i expect the log is like that:
----FixedUpdate
----OnTriggerStay2D
----FixedUpdate
----OnTriggerStay2D
....
but actually the log is lik this:
----FixedUpdate
----OnTriggerStay2D
----FixedUpdate
----FixedUpdate
----OnTriggerStay2D
....
i mean, sometimes two or more FixedUpdate log near each other and no OnTriggerStay2D between them!
i think this is a bug, because in early version of unity, like unity 5.2.1, no such problem.
i already subimited a bug here: https://fogbugz.unity3d.com/default.asp?849290_d2ha0o2mgkkj1lfa
↧
↧
Increasing performance with physics 2d settings
can anyone give me an example of increased performance physics 2d settings with low quality physics? My app is lagging in my android phone because of physics. I want to decrease quality of its settings. But I really dont know how to adust this settings by optimum way.
↧
Frictionless space
Hey I'm making a 2D space shooter, I have my player moving friction-less like I want and collisions with asteroids work, but when the player collides with an explosion the player slows down which is not what I want, the explosion is a circle that expands as the circle expands it pushes the player away, but when the explosion is destroyed the player no longer being pushed slows down, I want the player to keep it's velocity, but when the explosion is expanding and pushing the player the player's velocity does not seem to increase. I am using a physics material that is friction-less and I have tried using add force in OnCollisionEnter and Exit, but it does not seem to work right, I hope someone has a good answer
here is my explosion code:
public class Explosion : MonoBehaviour
{
CircleCollider2D cc;
void Start()
{
cc = GetComponent();
}
void Update()
{
if (GameManager.gameState != GameManager.GameStates.play)
return;
//increase the collider
cc.radius += Time.deltaTime/2;
//destroy object after 1.5 seconds
Destroy(gameObject, 1.5f);
}
}
Update: Sorry I didn't post my player code because there is nothing in it that slows down the player, also it happens with the asteroids when they hit the explosion as well, the increasing size of the collider is not causing the problem I just tried it with a fixed sized circle, the player and asteroid collisions work fine, it seems as the explosion collider expands it pushes the other objects away but does not effect other object's velocity for some reason..
Update 2:
Here is the code I spawn the explosion with:
public class LaserBeam : MonoBehaviour
{
float speed = GameManager.LIGHT_SPEED;
public Explosion explosion;
void Start()
{
this.GetComponent().AddForce(transform.up * speed);
}
void Update()
{
if (GameManager.gameState != GameManager.GameStates.play)
return;
//destroy object after 1 second
Destroy(gameObject, 1);
}
void OnCollisionEnter2D(Collision2D col)
{
if (GameManager.gameState != GameManager.GameStates.play)
return;
//destroy target
if (col.gameObject.tag == "Asteroid") //if (col.gameObject.tag != "Player")
{
Vector2 size = col.transform.localScale*4;
Destroy(col.gameObject);
//create explosion
explosion = Instantiate(explosion);
explosion.transform.position = col.transform.position;
explosion.transform.localScale = size;
//destroy object
Destroy(gameObject);
GameManager.playerScore += 50;
}
}
}
also my objects all have a 2d physics material with 0 friction and .666 bounciness
↧
Rigidbody2D.IsSleeping issue
When checking the velocity of an object with ...velocity.x == 0 && velocity.y == 0 everything works fine but if i use Rigidbody2D.IsSleeping there seems to be a small delay?
if (rb.IsSleeping)
{
// Calls after the rigidbody has stopped moving +0.2 - 0.3s
}
if (rb.velocity.x == 0 && rb.velocity.y == 0)
{
// Everything works fine but for reasons i can't use this
}
↧
↧
OnCollsionExit2D gets invoked wrongly even when the character is colliding with the object
Hi All,
This is my first post. I am trying to use Physics2D.IgnoreLayerCollision to ignore collision between the player and the platform when the player jumps from under it. It works fine without any issues. But when the platform is moving the code that I added for making the player to stick on the platform does not work.
Below is the Player update method:
void Update(){
if (transform.position.y <= fallBoundary) {
damagePlayer (99999);
}
//_vy is the velocity of the player in the y direction
_vy = r2d.velocity.y;
//ignore collision when jumping from below the platform
Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f));
}
I add the speed of the moving platform to the player when he is standing on it by using OnCollisionStay2D method and when the player leaves the platform I remove the speed by using OnCollsionExit2D method. The problem is that OnCollisionExit2D gets called even when the player is standing on the platform(**Note**:This does not happen when I dont use Physics2D.ignoreLayerCollsion).
Below are the OnCollsionStay2D and OnCollisionExit2D methods:
void OnCollisionStay2D(Collision2D colliderInfo){
//Debug.Log ("moving");
if (colliderInfo == null || colliderInfo.gameObject == null) {
Debug.Log ("return");
return;
}
if (colliderInfo.gameObject.tag.Equals ("Player")) {
PlatformerCharacter2D d = player.GetComponent ();
if (rightToleft) {
//Debug.Log ("rightToleft");
d.platformSpeed = -xvel;
} else {
//Debug.Log ("righttoleftfalse");
d.platformSpeed = xvel;
}
}
}
void OnCollisionExit2D(Collision2D colliderInfo){
PlatformerCharacter2D d = player.gameObject.GetComponent ();
d.platformSpeed=0f;
}
I am just curious as to why this happens. Thanks in advance for the help.
↧
Snake Movement Like in Snake vs Box
I am stuck at achieving snake movement of game Snake VS Box.
can anyone help me.
↧
How to enable the collision between two objects after using Physics2D.IgnoreCollision() ?
Hi, After using the Physics2D.IgnoreCollision() fonction,
I've been trying to re enable the collision between the object but I can't find any solution.
Is there any fonction that can do the opposite of Physics2D.IgnoreCollision() ?
Thanks for your help :)
(Ps: Disable and Enable the collider rather than using Physics2D.IgnoreCollision() is not a good alternative in my case)
↧
OnTriggerEnter2D first collision causes lag/freeze
Hey all,
I'm currently developing a mobile game and I ran into a small problem. When my player first collides with an enemy, the game freezes for a bit.
The weird thing is that this happens only when first time OnTriggerenter2D is called. Enemies that collide with my player afterwards do not cause any lag.
I profiled the game and it shows that three things cause this issue, specifically:
Physics2D.CompileContactCallbacks, Physics2D.SendContactcallbacks and Physics2D.SendTriggerContactCallbacks.
My player has a dynamic rigidbody2D attached as well as BoxCollider2D that has set OnTrigger to true.
The same applies to the enemies, except the rigidbody2D is set to kinematic.
Here's a screenshot from the profiler: https://i.imgur.com/RDVHeXg.png
I'm testing it on Samsung S4 mini.
Any ideas how to fix this?
Thanks!
↧
↧
How can I make 2D physics bounce the same as the 'multiply' bounce combine mode as seen in 3D Physics materials
In 3D physics materials, we have the setting of 'Bounce Combine' which dictates how the two physics materials bounciness values combine together to determine the overall bounce of the collision.
The choices are Average (of the two bounciness values), Minimum, Maximum, and Multiply which just multiplies the bounciness values together
Multiply is the mode I really want, but this setting of 'Bounce Combine' is just not available at all for 2D Physics materials, and the way it works by default is the equivalent of 'Maximum' in 3D.
One thing I tried to get multiplicative bounce was setting physics materials bounciness to 0 and instead use my own Bounce code:
void OnCollisionEnter2D(Collision2D collision)
{
float multipliedBounce = bounciness * collision.otherRigidbody.GetComponent().bounciness;
foreach (ContactPoint2D contact in collision.contacts)
{
Vector2 impactVelocity = contact.relativeVelocity;
float velocityInNormalDirection = Vector2.Dot(impactVelocity, contact.normal);
Vector2 force = contact.normal * velocityInNormalDirection * rb.mass * multipliedBounce;
rb.AddForceAtPosition(force, contact.point, ForceMode2D.Impulse);
}
}
This *kinda* works, but I feel like I'm doing something wrong because it doesn't act the same as the equivalent bounciness on a normal physics material, it bounces less on flat ground, but sometimes goes chaotic when colliding with other dynamic things, especially with box shapes, who's contact points can be in the far corners of the shape.
I would like to know if I'm doing something wrong in this code, or if there's any other solution entirely.
Thanks!
↧
2D muscle joint?
Hello!
I have two RigidBody2D's connected to each other by a HingeJoint2D. I'm looking for a way of connecting one or many "muscles" between them. Like a spring/distance joint that I can contract/expand, and thereby make the two rigidbodies move, like an arm for example. But if I have two of the muscle joints (I've tried with both distance and spring joints), and set the distance, the two muscle joints will fight each other making the rigid bodies swirl around like crazy.
Hope you understand what I mean. The best way I can show you what I'm after is this video:
https://www.youtube.com/watch?v=pgaEE27nsQw but it's 3D, so I want to mimic muscles like this for 2D rigidbodies. As you can see in the video each rigid body has many muscles connected to them.
Looking forward to see what approach you can recommend. :) Thanks in advance!
↧
When to use Effectors instead of scripting the behavior?
Performance wise or any other aspect, what are the scenarios that dictate the effectors as the right tool to use?
↧
How to change distance but maintain speed and height of jump
Suppose I have a block (RigidBody2d) traveling on a flat surface at a constant velocity to the right. The block jumps when the player presses the jump key, and the rigidbody has a force added onto it so that it jumps. What is the best way to change the amount of time that the block spends in the air moving up and "floating" down. E.G. it currently moves 20 units to the right when I press jump before landing, but now I want it to only move 10 units to the right. Additionally, the speed of the block and the jump height of the block should stay the same. The only thing changing is the distance traveled in the air.
Can this be done with the Unity2D physics engine?
↧
↧
Optimal way to check repeatedly close objects
Hi,
I am developing simple flammable object. I have made it but i am having second thoughts on implementation.
I have flammable object that can catch fire.Every flammable object that is on fire cast every 0.1sec OverlapCircleAll to check its surroundings for other flammable objects so it can fire them up. This works well on static and dynamic moving objects.
It works fine but I am having second thoughts about performance impact on lets say 100 objects casting OverlapCircleAll.
Any ideas to improve performance or I should not bother ?
Thanks.
↧
Ferr2d terrain physics material does not affect
I have sliding gameobject with polygon collider2D and two ferr2D terrains with different physic materials. First one have friction 0 and the second one 5. But when my gameobject slides throught/across those terrains, they both slow down the gameobject as much, so the friction seems to be the same in both. What's the problem here?
↧
How to detect what Gameobjects are in a Collider2D? (C#)
I am making a tower defense game (2D) and I am working on making the towers shoot the enemies. I want my turrent to shoot every 1 second and hit the enemy the closest to the front. My solution to this problem is by using circle colliders to detect if an enemy is in firing range, but I can not figure out how to shoot the enemy in first. I am stuck on trying to figure out how to put the enemies that are in the turrents range/collider2d in a list/enumerator/array (Whichever one is appropriate for storing gameobjects and can change length).
I looked through the documents and I couldnt find any collider2D function that lists the gameobjects in its range, so i need an alternative way to do it.
↧
Rigidbody2D is kind of flying instead of falling when the child box is colliding
Hi everyone,
I got a strange issue, everything is in the title, but i'll add some details :
I'm making a 2D side scroller game, the player can move on X and Y axes like in Castle Crashers. So the player has 2 objects : "**Body**" as parent which contains the **Rigidbody2D** and a **BoxCollider2D**, and "**Feet**" as **child** of "**Body**" which contains only a **BoxCollider2D**, which collides with some walls as you can see here :
![alt text][1]
When i press the jump key, the Y position of the "Feet" is stored, and a force is applied to the Rigidbody2D. During the jump, i set the "Feet" Y position with the one stored. On a normal behaviour it works fine, but if i go against a wall (as shown on the screen), during the jump, when the Body is supposed to go down, he flies (the body keeps a velocity of 0).
I guess the "Feet" collision breaks the "Body" Rigidbody2D stuff (i tried by adding a OnCollisionStay2D on the "Feet" object and it's returing true each frame).
Does someone knows how i can avoid that ? One solution is to make a "teleport" of 0.01f on top of the wall, but i would prefer to avoid this solution.
PS : i already have a Physics2D Material with 0 as friction on the player and the wall
PS2 : sorry for my bad english :/
[1]: /storage/temp/54440-bug-physique.png
↧
↧
Ground Check Issue
So ive been following the 2d controllers tutorial and he was covering the groundcheck and falling physics. The problem im having is that when the player is not on ground, the ground boolean does check off but the groundcheck dont let the player fall off at all. Please help!
↧
dropping series of masses connected by spring
I am trying to show how a series of 2D masses connected by string will fall. I have connected 10 masses with a spring joint. However they all fall at the same time. I would like to make the simulation such that their is initial tension and then the tension at the top is released so the bottom box does not fall until the rest of the masses have collapsed. Does anyone know how this would be done? What would I say in my script?
↧
How to see if two objects are touching each other
So, I am trying to check if two objects are touching each other, and this is the part of the script that I cant get to work
public static bool IsTouchingS (BoxCollider2D.StraightS, BoxCollider2D.PlayerCar);
void GetLocator ()
{
if (IsTouchingS == true)
↧