Unity bouncing ball with scripts - unity3d

how do I create a bouncing ball in unity that bounces to the same height and that I can make it fall quicker or slower? I've tried to do it from rigid body settings but the ball keeps climbing and I can't control the falling speed. Help

Multiply your desired height vector with a positive sine wave (negative values get multiplied by -1) and add this to your initial position of the ball.
To control the speed of the ball you can multiply the value you use to evaluate the sine function with another factor.
heightVector * |sin(time * speed)|

Related

How to make projectile travel with a curve trajectory to a targeted position in 3D

So I want to have my projectiles travel to a targeted position with in a certain amount of time and have a curve trajectory with a max height. I have watchh a couple youtube tutorials but they're just simply not want I need right now is there a way for me to do this ?
I followed this tutorial as first but I can't increase the speed and reduce the time and the height to my liking:
https://www.youtube.com/watch?v=Qxs3GrhcZI8
You have a targeted position implies that the distance between the user and the target is r (say). Now, you want the projectile to hit the target in a certain time t. Let's say the projectile was thrown at a velocity v. Below are the calculations that yield the result of how much velocity and angle of projection are required to achieve the hit in the given time t
The question says
have a curve trajectory with a max height.
Theoretically, the maximum height is achieved when the angle of projection is 90 degrees with respect to the ground and the cosine of 90 is 0. Substituting the value of cos(theta) in the resultant equation results in the value of velocity being infinity, which is practically impossible.
Hence, with the given range and time of flight, two variables, the velocity, and angle of projection can be configured. If the maximum height that you want to achieve is specified, the angle of projection is calculated accordingly.
Unity Slerp will be a good fit for you. You can specify the start, end point and also
control the time. You won't be able to control the height as its dependent on the Vectors.
Here is the Link to Unity Docs
https://docs.unity3d.com/ScriptReference/Vector3.Slerp.html

Moving a 2D physics body on a parabolic path with initial impulse in unity

What I have:
A projectile in Unity 5 2D, affected by gravity, that I want to move from point A to point B with initial impulse on a parabolic path
What I know:
The 2D coordinates of a random starting position (A)
The 2D coordinates of a random target position (B)
The time (X) I want the body to reach the target position after
What I want to know:
The initial impulse (as in unity applyforce with forcemode impulse) that I have to apply to the body onetime in order for it to reach the desired position B after X time.
Notes:
It is a 2D world using Unity 2D physics
The two positions A and B are totally random and may or may NOT be at equal heights (y coordinates)
I want to apply the impulse one time only when spawning the projectile
The projectile does NOT have any other forces affecting him other than GRAVITY (for the current problem lets assume that it always with magnitude 9.8 pointed down)
Here is a (bad) drawing of what I want :D
Thanks upfront guys!
Let's solve a few simpler problems. Our goal is to find an initial velocity for the particle, instead of an "impulse", because we'll achieve better control this way.
First, consider how we would solve this without Unity physics. A particle's position as a function of time depends on its initial position, velocity and acceleration. The same equations apply regardless of how many dimensions you have. This equation is:
current_position = 1/2 * acceleration * time^2 + velocity * time + starting_position
Let current_position be our desired destination, time be the duration of travel you choose, and the starting_position to be the starting position of the particle.
In the x-dimension, there is no acceleration. Let X_0 be our starting X position, X_1 be our destination, and T be the duration of time we want to spend getting to that destination. We want to find v_x, or the velocity in the x-dimension. For ease of interpretation, I've marked all the constants in uppercase and the variable in lowercase.
X_1 = v_x*T + X_0
v_x = (X_1-X_0)/T
In the y-dimension, we have gravity of some kind. So let's incorporate that as our acceleration:
Y_1 = 0.5*G*T*T + v_y*T + Y_0
v_y = (Y_1 - Y_0 - 0.5*G*T*T)/T
Now that you have v_x and v_y, just set the velocity:
rigidbody2d.velocity = new Vector2(v_x, v_y);
Since different objects have different mass, you don't want to try to calculate an impulse. Just set the velocity to what you want in the frame when the object is spawned.
This runs contrary to advice you might find elsewhere on the Internet, but try it first before doing something more complicated.
Some important notes:
Physics processing in Unity isn't stable: you might get different results on different platforms, especially between different mobile devices. If there is performance pressure, there may be fewer physics evaluations and therefore incorrect results. This is generally not a problem with 2D physics.
You may experience an issue with the scale of gravity, depending on your version and what other settings you have.
The formulas of position of a projectile influenced only by gravity are these:
x = x0 + v_x0*t
y = y0 + v_y0*t + 0.5*g*t^2
so, to know the starting velocity, with some basic calculations:
v_x0 = (x-x0)/t
v_y0 = (y-y0)/t + 0.5*g*t^2/t = (y-y0)/t - 4.9*t
Now, in order to add this startin velocity by using AddForce, we could have used ForceMode.VelocityChange, but this mode is only available for 3D rigidbodies, so we need to use the ForceMode.Impulse and multiplying the force by the mass of the object:
RigidBody2D rigid = GetComponent<RigidBody2D>();
rigid.AddForce(new Vector2 (v_x0, v_y0) * rigid.mass, ForceMode2D.Impulse);
and that's it.
Of course you can just set the velocity of the rigid body directly instead of using AddForce.

Zero-crossing detection in simulink

I would like to know when to enable/disable zero-crossing detection option in Simulink blocks. Please explain with an example. What happens if we disable the option and run the simulation ?
I know that zero-crossing detector will tell number of times signal is crossed zero or changed sign. But I want to know when we've to enable this and a real-time example with its use ?
Example of bouncing ball referred here can be seen in the link provided below by phil Goddard in his comment.
I understand the dynamics of bouncing ball. Initially a ball is thrown upward with initial velocity 15 m/s. So if we see the velocity plot, Initially velocity is decreasing and when ball reaches its top, velocity is zero and then ball starts to fall down and velocity is increasing in the -ve direction. when ball touches the ground, kinetic engery is converted into potential energy and little heat energy and again potential energy is converted to kinetic and ball starts to raise. That's why At position zero, velocity is again rise up to maximum and the same sequence follow. I ran the model with both zero-crossing detection enabled and disabled but I didn't see any difference in the scope plot.
Thanks in advance.
You can use a combination of sign block from simulink>math operations library and saturation block by adjusting the limits of saturation block to 1 and 0. Then do product with -1 followed by addition of 1 so that the output shows 1 when signal is below 0 and output is 0 when signal is above 0.
Block diagram of zero crossing detector:
&
Output of zero crossing detector:

Unity - Matching Speed While Transistioning From Traveling on a Single Axis to Rotation Around a Circle

I am working on a simple project that consists of a ball with a rigid body being pushed along the x axis. The ball needs to transition 90 degrees and continue straight up.
I've created a box to serve as a pivot/rotation point and placed it exactly 5 units above the beginning of the 90 degree transition from and exactly 5 units away from the end of the transition. I've created two colliders that work as triggers; one at the beginning and one at the very end of the 90 degree transition.
So my ball will come zooming along on the x axis and hit the first trigger. When it does I reset the ball's velocity to zero and parent the ball to the box serving as a pivot/rotation point. I've then applied angular velocity to the box so that the ball will rotate exactly 5 units around the pivot point. When the ball hits the second collider at the end of the transition it is un-parented and velocity is reapplied so the ball can continue straight up.
So here is the question; if the ball is 5 units away from the pivot point, the distance traveled for the 90 degree transition would be something like : 5 * 2 = the circles diameter * PI = 31.4 units distance around the circle / 4 = 7.84 game units to travel for the entire 90 degree transition.
So how do I match the velocity the ball had while traveling solely on the x axis so that it has the same speed while transitioning using the pivot point rigid body's moveRotation function around a circular axis?
If I have a velocity vector of (-10, 0, 0) when I hit the first trigger how do I calculate what to feed into the moveRotation function so that a the ball, rotating 5 units away from the pivot point, is still traveling at 10 units a second?
Taking the original velocity (-10, 0, 0) and multiplying by the distance needed to travel for the 90 degree transition(7.85 units) looks really close but I can figure out how to check it.

How can the friction drag be calculated for a moving and spinning disk on a 2D surface?

Let's consider a disk with mass m and radius R on a surface where friction u also involved. When we give this disk a starting velocity v in a direction, the disk will go towards that direction and slow down and stop.
In case the disk has a rotation (or spin with the rotational line perpendicular on the surface) w beside the speed then the disk won't move on a line, instead bend. Both the linear and angular velocity would be 0 at the end.
How can this banding/curving/dragging be calculated? Is it possible to give analytical solution for the X(v,w,t) function, where X would give the position of the disk according to it's initial v w at a given t?
Any simulation hint would be also fine.
I imagine, depending on w and m and u there would be an additional velocity which is perpendicular to the linear velocity and so the disk's path would bend from the linear path.
If you're going to simulate this, I'd probably recommend something like dividing up the contact surface between the disk and the table into a radial grid. Compute the relative velocity and the force at each point on the grid at each time step, then sum up the forces and torques (r cross F) to get the net force F and the net torque T on the disk as a whole. Then you can apply the equations F=(m)(dv/dt) and T=(I)(dw/dt) to determine the differential changes in v and w for the next time step.
For what it's worth, I don't think a flat disk would curve under the influence of either a frictional force (velocity-independent) or a drag force (linearly proportional to velocity).
A ball will move in a large arc with spin, but a [uniform] disk on a 2D surface will not.
For the disk it's center of spin is the same as it's center of gravity, so there is no torque applied. (As mentioned by duffymo, a nonuniform disk will have a torque applied.)
For a uniform ball, if the axis of the spin is not perpendicular to the table, this causes the ball to experience a rotational torque which causes it to move in a slight arc. The arc has a large radius, and the torque is slight, so usually friction makes the ball stop quickly.
If there was a sideways velocity, the ball would move along a parabola, like a falling object. The torque component (and the radius of the arc) can be computed in the same way you do for a precessing top. It's just that the ball sits at the tip of the top (err....) and the bottom is "imaginary".
Top equation: http://hyperphysics.phy-astr.gsu.edu/HBASE/top.html
omega_p = mgr/I/omega
where
omega_p = rotational velocity...dependent on how quickly you want friction to slow the ball
m = ball mass
g = 9.8 m/s^2 (constant)
r = distance from c.g. (center of ball) to center, depends on angle of spin axis (solve for this)
omega = spin rate of ball
I = rotational inertia of a sphere
My 2 cents.
Numerical integration of Newton's laws of motion would be what I'd recommend. Draw the free body diagram of the disk, give the initial conditions for the system, and numerically integrate the equations for acceleration and velocity forward in time. You have three degrees of freedom: x, y translation in the plane and the rotation perpendicular to the plane. So you'll have six simultaneous ODEs to solve: rates of change of linear and angular velocities, rates of change for two positions, and the rate of change of angular rotation.
Be warned: friction and contact make that boundary condition between the disk and the table non-linear. It's not a trivial problem.
There could be some simplifications by treating the disk as a point mass. I'd recommend looking at Kane's Dynamics for a good understanding of the physics and how to best formulate the problem.
I'm wondering if the bending of the path that you're imagining would occur with a perfectly balanced disk. I haven't worked it out, so I'm not certain. But if you took a perfectly balanced disk and spun it about its center there'd be no translation without an imbalance, because there's no net force to cause it to translate. Adding in an initial velocity in a given direction wouldn't change that.
But it's easy to see a force that would cause the disk to deviate from the straight path if there was an imbalance in the disk. If I'm correct, you'll have to add an imbalance to your disk to see bending from a straight line. Perhaps someone who's a better physicist than me could weigh in.
When you say friction u, I'm not sure what you mean. Usually there is a coefficient of friction C, such that the friction F of a sliding object = C * contact force.
The disk is modeled as a single object consisting of some number of points arranged in circles about the center.
For simplicity, you might model the disk as a hexagon evenly filled with points, to make sure every point represents equal area.
The weight w of each point is the weight of the portion of the disk that it represents.
It's velocity vector is easily computed from the velocity and rotation rate of the disk.
The drag force at that point is minus its weight times the coefficient of friction, times a unit vector in the direction of its velocity.
If the velocity of a point becomes zero, its drag vector is also zero.
You will probably need to use a tolerance about zero, else it might keep jiggling.
To get the total deceleration force on the disk, sum those drag vectors.
To get the angular deceleration moment, convert each drag vector to an angular moment about the center of the disk, and sum those.
Factor in the mass of the disk and angular inertia, then that should give linear and angular acclerations.
For integrating the equations of motion, make sure your solver can handle abrupt transitions, like when the disk stops.
A simple Euler solver with really fine stepsize might be good enough.