How can I balance a cube with a rigidbody in unity - c#

I am trying to have a cube rotate itself back to its orginal rotaion whenever the palyer bumbs in the cube but I don't want it to snap back instantly, I am trying to let it balance itself out and make it look jiggly but I do not how how to make it. I tried differnt ways but none of them work. This is my last try and I know that it is just checking one axis and so but I am clueless so can anybody tell me how to do this.
if(transform.rotation.z > 10)
{
transform.rotation = Quaternion.Slerp(transform.rotation, StartRot, TimeCount);
TimeCount = TimeCount + Time.deltaTime;
print("Go");
}

I would suggest looking at this first, and there are plenty of tutorials like this though that one is about a punching bag the concept is similer.

Related

#Unity Cube Movement (Jumping +1 Forward/Right/Backward/Left)

Hey stackoverflow Community,
First of all:
I'm still very new about programming with C# and Unity.
My question:
I'm working on an idea for a Movement of a Cube.
It is planned that the cube will move forward by pressing a key (W-Key). But it shouldn't just move forward. It should jump forward to the next point. So always plus 1 of its axis into which it should go. Accordingly, it is only intended to go forward, right, down, left. He won't be able to jump over behind. You should also see that the cube jumps in the respective direction, so it should not teleport itself. :D
Does anyone have an idea how I can realize this movement?
I am very much looking forward to your ideas.
(Sorry if my English is not so good, my English not the best. ^^)
best regards
xKarToSx
So, in order to understand movement, it's best to first understand Vectors in Unity. Since you want to be moving the cube in the forward direction, I'm going to assume this is a 3D game, in which case you want to use a Vector3.
A Vector3 has three components: X, Y, and Z. Each component is tied to an axis. In simple terms, X is tied to left and right, Y is tied to up and down, and Z is tied to forward and back. So, Vector3 position = new Vector3(0, 1, 2); will be a vector that is 1 unit above and 2 units in front of the starting position.
Assuming you've attached this script to the cube you want to move, you can track its position with transform.position. So, if you want to move the cube one unit forward, your code would look something like this:
if(Input.GetKeyDown(KeyCode.W)) // This code will activate once the user presses W.
{
transform.position += new Vector3(0, 0, 1);
}
That will move the cube one unit forward in the Z direction. However, you don't want it to teleport, you want to see it move, correct? In that case, you want to check out Unity's Vector3.Lerp function. Basically, you would use it to smoothly transition an object between two defined positions. You'll need to implement a timer and a for loop in order to make this work correctly.
So, to summarize, for moving one unit forward in the Z direction, your code would look something like this:
if(Input.GetKeyDown(KeyCode.Z))
{
float startTime = Time.time; //Time.time is the current in-game time when this line is called. You'll want to save this to a variable
float speed = 1.0f; //The speed if something you'll want to define. The higher the speed, the faster the cube will move.
Vector3 startPosition = transform.position; //Save the starting position to a different variable so you can reference it later
Vector3 endPosition = startPosition + Vector3.forward; //Vector3.Forward is equivalent to saying (0, 0, 1);
float length = Vector3.Distance(startPosition, endPosition); //You'll need to know the total distance that the cube will move.
while(transform.position != endPosition) //This loop while keep running until the cube reaches its endpoint
{
float distCovered = (Time.time - startTime) * speed; //subtracting the current time from your start time and multiplying by speed will tell us how far the cube's moved
float fraction = distCovered / length; //This will tell us how far along the cube is in relation to the start and end points.
transform.position = Vector3.Lerp(startPosition, endPosition, fraction); //This line will smoothly transition between the start and end points
}
}
I hope this helps you. This is my first time answering a question so sorry if I got some things wrong/it's not the most optimized. Good Luck!

Finding Landing point

I am using addforce to throw object into the air, I want to instantiate a plane in position of landing point, how can I do that? I was thinking to calculate the landing point with Unity Physics API but I don't know how.
I have tried some code about projectiling but it won't help
if (other.tag == "CarPlayer")
{
other.gameObject.GetComponentInParent<Rigidbody>().AddForce(0, 1 * power, 1 * power, ForceMode.Impulse);
}
I really need an algorithm to find actual point that the object is going to land
As far as I know you're gonna have to do the math yourself; Unity doesn't have a built in instant simulation of this.
There are plenty of resources online on this already, this wiki-page on Trajectory Simulation for instance, which could probably help you.
If you need to calculate the force etc (the opposite of what you're asking), have a look at this blog, where the required trajectory is calculated. Source code
The simplest answer is probably to use something like this:
public Vector3 PlotTrajectoryAtTime (Vector3 start, Vector3 startVelocity, float time)
{
return (start) + (startVelocity * time) + (Physics.gravity * time * time * 0.5f);
}
(Before you start explaining PEMDAS; yes, I know the parentheses aren't needed, but I think the visual grouping gives better readability, thus easier understanding of it)

For C# in Unity, how could I have a ball that has it's radius shrink by 0.1 units every second?

Just as the title asks. I've tried to figure this out on my own, but since I'm still new, I'm completely stuck on how I could do this. Thanks in advance.
I believe the code you'll need to make the change is something like:
transform.localScale = Vector3.Lerp (transform.localScale, targetScale, speed * Time.deltaTime);
You'll should set your targetScale and speed earlier in your script. If this were in your update function, I am not sure if it would continuously run 'every second' to the effect that you want. maybe you'll need a coroutine for that part.

How do I freeze rotation of a Rigidbody programatically?

I am creating a 2D platformer game, and I already wrote the script that moves the sprite forwards and backwards successfully. However, I am extremely new to Unity and C#, so I have no idea how to freeze rotation of the sprite.
I tried to do it programatically (because the use gravity option did not appear in inspector) like so-
void Update () {
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
rb2d.freezeRotation.freezeRotation = true;
}
but it obviously doesn't work. How do I correctly freeze rotation of the sprite with c#? Where do I put this code?
Thanks in advance-
George :)
What you could do to constraint the rotation on one axis of your object is:
Create a variable float freezeRotationX = 5.0f; //5.0 is just an example
And write this transfrom.rotation = Quaternion.Euler(freezeRotationX, transfrom.rotation.y, transfrom.rotation.z); This line should be in the Update methode.
This will fix the rotation on the X axis and leave the other ones with their current value.
Of course you can create a variable for each axis.
Hope that helps you.
This is very simple, you really don't have to use C#, you can just set the angular velocity of a rigidbody2D really high, but if that doesn't work, try constantly setting the transforms rotations to 0, (the code would look like this in the update function,
getcomponent<yourgameobject>().transform.rotation.z = 0
getcomponent<yourgameobject>().transform.rotation.x = 0
getcomponent<yourgameobject>().transform.rotation.y = 0
the syntax probably isn't correct, and it might slow down the game, but if your beginning unity it is a simple solution.

How to apply force to an object in a particular direction in Unity

I'm using unity to develop my game. I've made a custom swipe gesture by calculating the startPosition and the end Position of the touch. I got the vector direction by subtracting the two positions and debugged it successfully.
But when it comes to applying force to my game object I'm not getting any success after trying a lot.
here's what I'm doing:
swipeDirection = new Vector3(endPos.x - startPos.x,0f, endPos.z - startPos.z);
swipeDirection.Normalize();
Debug.Log("The direction is "+ swipeDirection);
ball.rigidbody.AddForce(swipeDirection * 5);
where ball is just a GameObject. Whenever I run it on my iPhone, the game just gets stuck giving a EXC_BAD_ACCESS code after the first swipe.
So I just tested your code. And it works. This issue you may be having is that those number are pretty small most likely, and you need a LOT of force to move it noticeably. Try changing your 5 to a 1000 or something big so you can definitely see the change. Here is my code, just added to a ball with rigidbody.
void Start ()
{
Vector3 dir = new Vector3 (100f, 0f, 0f);
dir.Normalize ();
this.gameObject.rigidbody.AddForce (dir * 100);
}
almost identical. you just need to make the multiplier big enough to see.
good luck.

Categories