2d Ball character controller - c#

I wish to create a ball character similar to red ball game in unity 2d but I can't seem to get it to work like the one in red ball. I wish for the ball to ROLL left and right and be able to Jump. I managed to make it roll left and right by adding a physics material and bumping up the friction and adding the rb.AddForce() function but I am having trouble with the jumping. I tried rb.velocity() but when I jump and move right or left, the ball adds force too strongly and it just moves too swiftly . Am I missing something or is there a better way of doing this? I need help.....

A quick fix for this would be to define an upper limit. Like:
float limit = 10f;
Rigidbody2D rig;
void Start(){
rig = gameObject.transform.GetComponent<Rigidbody2D>();
}
void Update(){
if(Input.GetKeyDown(KeyCode.A && rig.velocity.magnitude < limit){
rig.AddForce(accelerationVariable);
}
}
I would use Rigidbody.velocity.magnitude because it gives you the length of the vector.
If you just want to check the x-Force use Rigidbody.velocity.x
Hope that helps

Related

Change default collider bounce direction in Unity

I'm creating a Breakout clone in Unity and want to change the direction of the ball based on if the ball hits the left side or the right side of the paddle, as in the original version of the game. What is the best way of accomplishing this? I tried adding angled colliders to my paddle, but that causes the ball to fall slightly through the paddle before hitting the collider and changing direction.
You should have access to the rigid body that you are colliding with, which will tell you the angle you want to bounce at. Then, you do a late modification of the trajectory ("late" as in after your physics are calculated and applied for velocity). Something like this should work:
Rigidbody2D.velocity = newDirection.normalized * Rigidbody2D.velocity.magnitude;

How can I make my rigid body bullets shoot in a straight line no matter my mouse movement?

I'm making a very simple 3D game in Unity where I have this space shuttle I can move around in space around asteroids and I can shoot when pressing/holding the mouse button. I'm doing this by Instantiating a sphere at the "Emitter" transform.position and then just applying a forward Force to that bullet object.
It all works fine, but the one thing I don't like and also don't know how to fix is how the bullets keep their position when shooting and moving the mouse left-right, instead of keeping a perfectly straight line at all times.
This is how it looks when I'm shooting and moving my camera at the same time:
Screenshot while shooting
Here's a gif for better visualization.
Right now it looks like I'm pissing lasers, which is never good. I tried making the bullet speed a lot faster, but then the bullets become harder and harder to see and it doesn't look as good.
This is the code by which I'm shooting the bullets:
private void Fire()
{
GameObject bullet = Instantiate(laserPrefab);
GameObject bullet2 = Instantiate(laserPrefab);
Physics.IgnoreCollision(bullet.GetComponent<Collider>(), shuttleCollider.GetComponent<Collider>());
Physics.IgnoreCollision(bullet2.GetComponent<Collider>(), shuttleCollider.GetComponent<Collider>());
bullet.transform.position = laserEmitter.position;
bullet2.transform.position = laserEmitter2.position;
/*Vector3 rotation = bullet.transform.rotation.eulerAngles;
Vector3 rotation2 = bullet2.transform.rotation.eulerAngles;
bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);
bullet2.transform.rotation = Quaternion.Euler(rotation2.x, transform.eulerAngles.y, rotation2.z);*/
bullet.GetComponent<Rigidbody>().AddForce(laserEmitter.forward * laserSpeed, ForceMode.Impulse);
bullet2.GetComponent<Rigidbody>().AddForce(laserEmitter.forward * laserSpeed, ForceMode.Impulse);
StartCoroutine(DestroyBulletAfterTime(bullet, bulletDeathTime, bullet2));
}
Don't mind the commented lines, I was just messing around trying to see if I can get it to work. The shooting behaves the same with or without those commented lines.
Of course, a projectile based system will behave and look like a projectile system.
If you want laser behavior use a LineRenderer. Raycast where your laser line should end (either laser max distance or the point of hitting an object in range).
If you don't like the "static" looks of it, change the LineRenderer Material to something that changes over time (search for shaders/ LineRenderer effects).

How do I fix the floating glitch that is happening to my Player Ball?

I am using Unity3D to make a replica of the game "Rolling Sky" which you can find on the Google/Apple app store. I was able to make a simple floor which the ball will move on and I was also able to make the ball (Player) move left and right. After moving the ball a couple of times back and fourth, it starts float in the air and eventually what it seems like is change it's axis.
I came up with a couple of alternatives that I think would work, but I had trouble coming up with the code to make it function properly.
1) Do not rotate the ball at all. Just have it smoothly move back and forth.
^^ Probably the best solution I could come up with.
or
2) Use CharacterController to have complete control of how the ball reacts to different events, scenarios, etc.
^^ This would probably be the most necessary and hardest of I had to guess.
or
3) Move the ball an x amount of pixels everytime I move left or right.
^^ I would assume this would create a lot more glitches than what I have right now.
public class PlayerController : MonoBehaviour
{
public float speed;
void Update()
{
transform.Translate(Vector3.right * speed * Input.GetAxis("Horizontal") * Time.deltaTime);
}
}
EDIT:
I was able to provide my own answer, but if anyone has any alternatives, feel free to post your solution!
To prevent the player ball from floating into the sky, no other code was needed. Simply go to the Rigidbody component on the Player and expand the "Constraints" menu. Next, check the axis boxes that you would like to freeze the rotation on to prevent the ball from spinning like so in the picture.
Click the link to see the picture
here.
In this case, I did not freeze the ball on the x axis because I eventually want to animate it to spin as if it is rolling forward.
You're using transform.Translate
and
You're using Vector3.right
transform.Translate will directly move the ball without thought of rotation. You will need to take the object's rotation into consideration when translating. You can also use the physics engine and use Rigidbody.MovePosition to force position or Rigidbody.AddForce to utilize physics interactions.
Vector3.right will use the constant value equivalent to Vector3(1, 0, 0). This will not be in regard to the object's rotation or facing.
I suggest looking through Unity's tutorial for a ball-roller and see how they complete the task of user input with a user controlled ball.

Transition Forward is going backward

I am a newbie to unity. In my project, the ball should instantiate in the player
position and it should go randomly 40 to 120 degrees from the player position.
I am using transition.forward. My player is constantly in running. when the player stands the ball is going correctly in front of the player.
but when the player runs the ball is going backward
How can I move towards randomly in front of the player? Like a ball
I am using the below code.
transform.Translate(Vector3.forward*5f );
There is a chance it might be fixed if you spawn the ball in front of the character. Since it works when the player is stationary, it might be conflicting with the collider of player when it is moving.
Also translating will just move the ball, not give it a velocity or anything. You should take a look at https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
So, first translate the ball forward and see if it spawned in the right location.
Then add a force vector to the ball's rigid body in the direction you like.
Something like:
ball.transform.Translate(Vector3.forward*5f);
float thrust = 10;
var rb = ball.GetComponent<Rigidbody>();
rb.AddForce(transform.forward * thrust);

Creating a buoyant boat in Unity

I need to find a way to make a 3D boat, appear to be buoyant in the water. Currently I am using a boat with a flat bottom and making it slide along the terrain, which is just below the water. This is giving the illusion of buoyancy, but not really what I'm looking for.
The boat moves using
this.transform.Translate(Vector3.left * Time.smoothDeltaTime * ((speed) + 1));
The boat turns using
this.transform.Rotate(Vector3.forward*Time.smoothDeltaTime*(int)(30*horizontal));
The boat has a RigidBody that uses gravity, does not interpolate, and has a Continuous Dynamic collision Detection. It also uses a convex Mesh Collider, with Smooth Sphere Collisions.
The Water has a Box Collider that is used as a trigger.
Now I need a way to make the boat seem to float in the water programmatically.
That means it
Wobbles when it hits something
Doesn't touch the bottom of the "river"
Corrects its rotation to stay flat on the river (doesn't stay crooked after hitting an island or other obstacle)
I would like to do this so that I can give the base of my boat the correct shape so that it can have more realistic collisions with underwater obstacles.
Additional to my comment, if really you want it to be buoyant, you have to make it non-kinematic and react to gravity and the water has to bee a volumetric mesh (or a box as you use, but that's less accurate, do not work with waves if you use water with wave effect).
Basically you'd want to add (at least) 4 objects to your boat and place rigidbody inside it and a script which will apply an upward force which is greater than your gravity.
Then in your OnCollisionStay method set a bool. Maybe something like this (on top of my head)
using UnityEngine;
using System.Collections;
public class Buoyancy : MonoBehaviour {
public float UpwardForce = 12.72f; // 9.81 is the opposite of the default gravity, which is 9.81. If we want the boat not to behave like a submarine the upward force has to be higher than the gravity in order to push the boat to the surface
private bool isInWater = false;
void OnTriggerEnter(Collider collidier) {
isInWater = true;
rigidbody.drag = 5f;
}
void OnTriggerExit(Collider collidier) {
isInWater = false;
rigidbody.drag = 0.05f;
}
void FixedUpdate() {
if(isInWater) {
// apply upward force
Vector3 force = transform.up * UpwardForce;
this.rigidbody.AddRelativeForce(force, ForceMode.Acceleration);
Debug.Log("Upward force: " + force+" #"+Time.time);
}
}
}
And place this on all 4 buoyancy objects (together with a collider or trigger of course). When the object is in water, it will push the boat upwards, if it's over the water, it will be pulled down by the gravity until it reaches water again where it will be pulled up again until it finds a balance.
P.S. If you want to move the boat, you will use the this.rigidbody.AddForce(Vector.forward * 5, ForceMode.Force) (or ForceMode.Accelerate) to move the boat
Use the Buoyancy script. Just add this to the boat, and add the water level (its y value) in the code. Also it is best to use addForce instead of translate to move the boat.
If you want to make the boat react more realistically, you should also put its center of gravity lower, this way it will "wobble" and it stays right side up.

Categories

Resources