Bullet hinge constraint, force appliance to achieve a clip like feature - physics

Is it possible, and if yes, how do I apply force in Bullet, if I have two objects connected with a hinge constraint and something is making them to open up a bit more?
So is it possible to give some kind of resistance force to the hinge constraint?
example: a clip
example: I have a V like shape, to which from the open part I push something that makes the V wider. But now I need to apply force on the object from the two legs of V.
(If relevant: Bullet version: bullet-2.82-r2704)

Bullet has a function to apply force to rigid bodies:
void btRigidBody::applyForce(const btVector3 &force, const btVector3 &rel_pos)
Reference: http://bulletphysics.org/Bullet/BulletFull/classbtRigidBody.html#af016720c45cf7ccaf8701d81a28319d9
First, to achieve the clip like hinge constraint, you have to create a hinge constraint.
Reference: http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints#Hinge
Next, you have to apply an angular force to both legs with opposite direction. So the force that pulls the clips together depends on the angle between the two "legs".
(In addition, you can set a limit for the hinge constraint to stop it at a specified angle).

Related

Making cylindrical space in Repast Simphony?

I am trying to model the interior of an epithelial space and am stuck on movement around the interior edges of a cylindrical space. Basically, I'm trying to implement StickyBorders and keep agents on those borders in a cylindrical space that I am creating.
Is there a way to use cylindrical coordinates in Repast Simphony? I found this example (https://www.researchgate.net/publication/259695792_An_Agent-Based_Model_of_Vascular_Disease_Remodeling_in_Pulmonary_Arterial_Hypertension) where they seem to have done something similar, but the paper doesn't explain methods in much depth, and I don't believe this is an example in the repast simphony models.
Currently, I have a class of epithelial cells that are set up to form a cylinder and other agents start just inside that cylinder. To move, they are choosing their most desired spot (similar to the Zombie code) then pointing to a new location in the direction of that desired location within one grid square of that original location. They check that new point before moving to it and make sure that there are at least two other epithelial cells in the immediate moore neighborhood, to ensure they stay against the wall.
GridPoint intendedpt = new GridPoint((int)Math.rint(alongX),(int)Math.rint(alongY),(int)Math.rint(alongZ));
GridCellNgh<EpithelialCell> nearEpithelium = new GridCellNgh<EpithelialCell>(mac_grid, intendedpt, EpithelialCell.class, 1,1,1);
List<GridCell<EpithelialCell>> EpiCells = nearEpithelium.getNeighborhood(false);
int nearbyEpiCellsCount=0;
for (GridCell<EpithelialCell> cell: EpiCells) {
nearbyEpiCellsCount++;
}
if (nearbyEpiCellsCount<2) {
System.out.println(this + " leaving epithelial wall /r");
RunEnvironment.getInstance().pauseRun();
//TODO: where to go if false
}
I am wondering if there is a way to either set the boundaries of the space to be a cylinder or to check which side of the agent is against the wall and restrict its movement in that direction.
The sticky border code (StickyBorders.java) essentially just checks if the point that the agent moves to is beyond any of the space's dimensions, and if so the point is clamped to that dimension. So, for example, if the space is 3x4 and an agent's movement would take it to 4,2, then that point becomes 3,2 and the agent is placed there. Can you do something like that in this case? If not, can you edit your question to explain why not and maybe that will help us understand better.
The approach we took in that model was to use a 3D grid space with custom borders and query methods. The space itself was still Cartesian - we just visualized it as a cylinder using custom display code. Using the Cartesian grid was an reasonable approximation for this application since the cell dimensions were significantly smaller that the vessel radius, so curvature effects were neglected. The boundary conditions on the vessel space were wrap around in the angular dimension, so that cells could move continuously around the circumference of the vessel, and the axial boundary conditions were also wrapped, as we assumed a long enough vessel length that this would be reasonable. The wall thickness dimension had hard boundaries at the basement membrane (y=0) and at the fluid interface (y=wall thickness).
Depending on which type of space you are using, you will need to implement a PointTranslator or GridPointTranslator that performs the border functions. If you want specific examples of the code I suggest you reach out to the author's directly.

Can I apply here Liskov substitution principle

I have two data models which are represented by the following classes:
1) ImagesSet - an object that owns 2DImage's, each 2DImage has its own position (origin(3DPoint), x-,y-axes(3DVector) and dimension along x and y axes(in pixels)), but the same pixel size(in mm for example), angle between x and y axes(90 degrees)
This object has following methods(in pseudo code):
AddImage(2DImage);
RemoveImage(ImageIndex);
number GetNumberOfImages();
2DImage Get2DImage(ImageIndex);
2) 3DImage - an objects that is similar to the first but with following restrictions:
it can store 2D images only with the same x-,y-axes and dimensions along x and y axes.
Is it correct in this case to derive 3DImage from ImagesSet?
From my point of view 3DImage "is a" ImagesSet (but with small restrictions)
Could I apply here Liskov substitution principle?
In this case if we are trying to add an image with another x,y axes - method AddImage either will throw an exception or return an error.
Thanks in advance,
Sergey
I agree with maxim1000 that LSP will be violated because derived class adds restrictions that are not present in the base class. If you take a close look at your description you will notice that the question can be turned upside-down: Can ImageSet derive from 3DImage?
Your situation is somewhat similar to Ellipse-Circle problem. Which one derives from the other? Is circle an ellipse with a constraint, or is an ellipse a circle with additional radius? The point is that both are wrong. If you constrain ellipse to equal radiuses, then client which attempts to set different values would receive an error.
Otherwise, if we say that ellipse is just a less constrained circle, we get a more subtle mistake. Suppose that shapes may not breach boundaries of the screen. Now suppose that a circle is replaced with an ellipse. Depending on which coordinate was tested, the shape might break out of the screen area without changing the client code. That is the exact violation of LSP.
Conclusion is - circle and ellipse are separate classes; 3DImage and ImageSet are separate classes.
May be it's just me, but whenever I hear "derive or not derive" my first reaction "not derive" :)
Two reasons in this case:
LSP is violated exactly because of those "small restrictions". So until you have AddImage in your base class which allows to add an image with any orientation, 3DImage is not an ImagesSet. There will be no way for algorithms to state that they need this feature (and comments is not a good place :) ), so you'll have to rely on run-time checks. It's still possible to program in this way, but this will be one more overhead for developers.
Whenever you create some abstraction, it's important to understand why exactly it's created. With derivation you implicitly create an abstraction - it's interface of 3DImage. And instead of this it's better to create this abstraction explicitly. Create an interface class, list there methods useful for algorithms able to work on both data structures and make both ImagesSet and 3DImage implementing that interface possibly adding some other methods.
P.S.
And likely AddImage will become one of those added methods - different in ImagesSet and 3DImage, but that depends...
Dear maxim1000 and sysexpand,
Thanks for the answers. I agree with you. It is clear now that LSP is violated and in this case I can't derive 3DImage from ImagesSet.
I need to redesign the solution in the following way:
2DImage will contain:
2DDimension's
PixelSize(in mm)
PixelData
2DImageOrientated will be derived from 2DImage and will contain new data:
3DPoint origin,
3DVector x-,y-axes
I will create pure interface IImagesSet:
number GetNumberOfImages()
RemoveImage(ImageIndex)
2DImageOrientated Get2DImage()
ImagesSet will be derived from IImagesSet and will contain the following:
vector<2DImageOrientated>
Add2DImage(2DImageOrientated)
number GetNumberOfImages()
RemoveImage(ImageIndex)
2DImageOrientated Get2DImage()
3DImage will be also derived from IImagesSet and will contain the following.
vector<2DImageOrientated>
Add2DImage(2DImage)
SetOrigin(3DPoint)
SetXAxis(3DVector)
SetYAxis(3DVector)
number GetNumberOfImages()
RemoveImage(ImageIndex)
2DImageOrientated Get2DImage()
In this case I think LSP is not violated.

creating table border in unity3d

I am working on a pool game of sorts. To create a table, I have used cubes as sides. I want to use the inbuilt physics engine to get those sides interact with the balls. Sadly I am unable to get it working.
Here is what I have done. I created cube as side, and a sphere for ball. To move the sphere, I am using rigidbody.MovePosition function. both the cube and sphere have colliders and rigidbody attached, and gravity turned off.
Sphere movement is fine, but when it collides with cube, it makes the cube fly. Since the cube is supposed to be an immovable wall, I constrained all axes rotation and movement. But, using constraints cause physics engine to go bonkers. Instead of sphere coming to stop or moving in opposite direction, it simply passes through the cube. Clearly, something is wrong, and I need help figuring out the same.
Thanks in advance.
Here is the code used to move the sphere.
public float movePower = 10.0f;
// Update is called once per frame
void Update ()
{
if(Input.GetKey(KeyCode.LeftArrow))
{
rigidbody.MovePosition(transform.position + Vector3.left* movePower * Time.deltaTime);
}
if(Input.GetKey(KeyCode.RightArrow))
{
rigidbody.MovePosition(transform.position + Vector3.right* movePower * Time.deltaTime);
}
if(Input.GetKey(KeyCode.DownArrow))
{
rigidbody.MovePosition(transform.position + Vector3.down* movePower * Time.deltaTime);
}
if(Input.GetKey(KeyCode.UpArrow))
{
rigidbody.MovePosition(transform.position + Vector3.up* movePower * Time.deltaTime);
}
}
The simplest way is to remove the Rigidbody from all cubes as they are supposed to be fixed. Another way is to mark the cubes' Rigidbody components as Kinematic, but this meant to be used for moving objects like player characters that should participate in physics but should not be moved by the engine.
I recommend reading the Unity Physics man page.
Update:
More things to consider:
Don't check Is Trigger
Check that your Layer Collision Matrix is set up right (menu Edit/Project Settings/Physics)
If the velocity is pretty high, physics engine might get confused and collision are not detected
Ensure that the models are not scaled down or up extremely (best is to have scale = 1)
The best mass for Rigidbody.mass is 1
Be careful when playing with PhysicsManager settings like Min Penetration For Penalty or Solver Iteration Count
Use gravity if possible
Never move by manipulating Transform directly. Use Rigidbody methods instead
Avoid calling rigidbody.MovePosition on every update if it's a constant linear motion. Do it once and leave it untouched
Remember to use FixedUpdate for calling rigidbody.MovePosition etc.

Projectile hit coordinates at the apex of its path

I have a projectile that I would like to pass through specific coordinates at the apex of its path. I have been using a superb equation that giogadi outlined here, by plugging in the velocity values it produces into chipmunk's cpBodyApplyImpulse function.
The equation has one drawback that I haven't been able to figure out. It only works when the coordinates that I want to hit have a y value higher than the cannon (where my projectile starts). This means that I can't shoot at a downward angle.
Can anybody help me find a suitable equation that works no matter where the target is in relation to the cannon?
As pointed out above, there isn't any way to make the apex be lower than the height of the cannon (without making gravity work backwards). However, it is possible to make the projectile pass through a point below the cannon; the equations are all here. The equation you need to solve is:
angle = arctan((v^2 [+-]sqrt(v^4 - g*(x^2+2*y*v^2)))/g*x)
where you choose a velocity and plug in the x and y positions of the target - assuming the cannon is at (0,0). The [+-] thing means that you can choose either root. If the argument to the square root function is negative (an imaginary root) you need a larger velocity. So, if you are "in range" you have two possible angles for any particular velocity (other than in the maximum range 45 degree case where the two roots should give the same answer).
I suspect one trajectory will tend to 'look' much more sensible than the other, but that's something to play around with once you have something working. You may want to stick with the apex grazing code for the cases where the target is above the cannon.

How to create an "intercept missile" for a game?

I have a game I am working on that has homing missiles in it. At the moment they just turn towards their target, which produces a rather dumb looking result, with all the missiles following the target around.
I want to create a more deadly flavour of missile that will aim at the where the target "will be" by the time it gets there and I am getting a bit stuck and confused about how to do it.
I am guessing I will need to work out where my target will be at some point in the future (a guess anyway), but I can't get my head around how far ahead to look. It needs to be based on how far the missile is away from the target, but the target it also moving.
My missiles have a constant thrust, combined with a weak ability to turn. The hope is they will be fast and exciting, but steer like a cow (ie, badly, for the non HitchHiker fans out there).
Anyway, seemed like a kind of fun problem for Stack Overflow to help me solve, so any ideas, or suggestions on better or "more fun" missiles would all be gratefully received.
Next up will be AI for dodging them ...
What you are suggesting is called "Command Guidance" but there is an easier, and better way.
The way that real missiles generally do it (Not all are alike) is using a system called Proportional Navigation. This means the missile "turns" in the same direction as the line-of-sight (LOS) between the missile and the target is turning, at a turn rate "proportional" to the LOS rate... This will do what you are asking for as when the LOS rate is zero, you are on collision course.
You can calculate the LOS rate by just comparing the slopes of the line between misile and target from one second to the next. If that slope is not changing, you are on collision course. if it is changing, calculate the change and turn the missile by a proportionate angular rate... you can use any metrics that represent missile and target position.
For example, if you use a proportionality constant of 2, and the LOS is moving to the right at 2 deg/sec, turn the missile to the right at 4 deg/sec. LOS to the left at 6 deg/sec, missile to the left at 12 deg/sec...
In 3-d problem is identical except the "Change in LOS Rate", (and resultant missile turn rate) is itself a vector, i.e., it has not only a magnitude, but a direction (Do I turn the missile left, right or up or down or 30 deg above horizontal to the right, etc??... Imagine, as a missile pilot, where you would "set the wings" to apply the lift...
Radar guided missiles, which "know" the rate of closure. adjust the proportionality constant based on closure (the higher the closure the faster the missile attempts to turn), so that the missile will turn more aggressively in high closure scenarios, (when the time of flight is lower), and less aggressively in low closure (tail chases) when it needs to conserve energy.
Other missiles (like Sidewinders), which do not know the closure, use a constant pre-determined proportionality value). FWIW, Vietnam era AIM-9 sidewinders used a proportionality constant of 4.
I've used this CodeProject article before - it has some really nice animations to explain the math.
"The Mathematics of Targeting and Simulating a Missile: From Calculus to the Quartic Formula":
http://www.codeproject.com/KB/recipes/Missile_Guidance_System.aspx
(also, hidden in the comments at the bottom of that article is a reference to some C++ code that accomplishes the same task from the Unreal wiki)
Take a look at OpenSteer. It has code to solve problems like this. Look at 'steerForSeek' or 'steerForPursuit'.
Have you considered negative feedback on the recent change of bearing over change of time?
Details left as an exercise.
The suggestions is completely serious: if the target does not maneuver this should obtain a near optimal intercept. And it should converge even if the target is actively dodging.
Need more detail?
Solving in a two dimensional space for ease of notation. Take \vec{m} to be the location of the missile and vector \vec{t} To be the location of the target.
The current heading in the direction of motion over last time unit: \vec{h} = \bar{\vec{m}_i - \vec{m}_i-1}}. Let r be the normlized vector between the missile and the target: \vec{r} = \bar{\vec{t} - \vec{m}}. The bearing is b = \vec{r} \dot \vec{h} Compute the bearing at each time tick, and the change thereof, and change heading to minimize that quantity.
The math is harrier in 3d because of the need to find the plane of action at each step, but the process is the same.
You'll want to interpolate the trajectory of both the target and the missile as a function of time. Then look for the times in which the coordinates of the objects are within some acceptable error.