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.
Related
I want a sprite to always face the camera, except in the Z-Axis. My sprites keep tipping left or right when I move the camera, and I can't have that.
I have been googling this for hours. I've tried transform.LookAt or Quaternion.LookRotation and manually setting the z to 0, but for whatever reason the z keeps adjusting. I've seen and tried so many solutions that feel like they should work but just don't. If it matters, my sprite is a child of another object, but trying localRotation doesn't work either. Freezing rigidbody constraints also has no effect.
The most accurate I can get it is this:
public class Billboard : MonoBehaviour
{
GameObject cam;
float minDist;
// Start is called before the first frame update
void Start()
{
cam = GameObject.Find("Main Camera");
}
// Update is called once per frame
void LateUpdate()
{
//Scale
minDist = cam.GetComponent<CameraOrbit>().distanceMin;
transform.localScale = new Vector3(1f, 1f, 1f) * (cam.GetComponent<CameraOrbit>().distance - minDist) * 1.01f / 3;
//Direction
transform.LookAt(cam.transform.position);
Vector3 rot = transform.rotation.eulerAngles;
transform.rotation = Quaternion.Euler(rot.x, rot.y, 0);
}
}
With this I can get the sprite to face the camera, but the z axis refuses to stay at zero.
Special thanks to StarManta for answering this question on the Unity Forums.
"OK, I think I see what's happening. Them looking like they're rotated is, I think, an illusion; I think they really are accurately pointing at the camera and right-side-up. But, you're treating the camera as if it has a round/fisheye projection, when it really has a rectilinear projection. Usually this doesn't matter but in this case it does. It's hard to explain exactly how this affects this, but the upshot is that, when things that are on either side of the center of the screen are set to "look towards" the camera, they actually appear to be rotated around their Y axes.
The solution to this is actually annoyingly simple: don't set the rotation to look at the camera, set it to be the same as the camera."
transform.rotation = cam.transform.rotation;
Have you tried rotation constraints?
https://docs.unity3d.com/Manual/class-RotationConstraint.html
I had a similar problem, where I wanted some 3d text to always look up, but rotated to the camera.
What worked for me was setting the undesired euler components to zero after applying the lookat rotation.
In your case, it would be something like this.
transform.LookAt(cam.transform.position);
var rot = transform.rotation.eulerAngles;
transform.rotation = Quaternion.Euler(rot.x, rot.y, 0);
In case you need another z value, just replace the 0.
In my 2D side-scrolling game I move my character using the built-in physics engine by manipulating the rigidbody.velocity.
I would like to add some sort of dodge (roll) ability, where the character moves 3 units in its direction.
Here is the code I used:
void FixedUpdate() {
if (Input.GetKeyDown(KeyCode.A) ) {
Vector2 pos = rb.position;
pos.x -= 5;
rb.MovePosition (pos);
}
}
This method works but the character kind of jumps to the position rather than moving to it (Lerping?) and also doesn't detect collisions despite the body type being dynamic.
Then I tried this:
if (Input.GetKeyDown(KeyCode.A)) {
rb.AddForce(new Vector2(-50, 0));
}
I found the AddForce way isn't accurate at all.
Is there a proper way of doing this?
Maybe you could change the Transform.pos inside Vector2.Lerp to make it look smooth? (Sorry, not enough experience with 2D in unity.)
Just increase rigibody.velocity for a set time. Your chararter object could then play a fitting aniamtion. If The player should not be able to cancle midrole jsut block the controls for that time.
I have found a solution for this if I were to be using translation as a means of movement:
http://answers.unity3d.com/questions/1035804/how-do-you-make-an-omnidirectional-2d-character-co.html
however I cannot find a solution for how to do this with my movement being physics based.
I have in my chracters controller the ability to rotate the camera around the z axis:
public Transform target;
private float cameraRot = 3;
if (Input.GetKey("q"))
{
target.transform.Rotate(0, 0, cameraRot);
}
I then have a script on all sprites in the world I am creating that rotates to always face the camera:
public Transform target;
void Start () {
target = GameObject.Find("MainCamera").GetComponent<Transform>();
}
void Update () {
if (target != null)
this.transform.rotation = Camera.main.transform.rotation;
}
That all works fine. However when I have rotated the camera, and therefore the sprites. The rigidbody movements become all skewed as they are rotating in the "global" space and not the "local".
I have tried placing the facecamera script on the child objects only to leave the rigidbody alone but this has no effect.
I hope I made this clear enough and that someone can help.
thank you very much for your time, if I find a solution I will mark the answer as correct and if I fix this myself before an answer I will update with how I fixed it.
The solution was to use:
Rigidbody.AddRelativeForce(Vector2.down * speed);
in lieu of:
Rigidbody.AddForce(Vector2.down * speed);
that adds the force in the local axis not the global.
documentation is here:
https://docs.unity3d.com/ScriptReference/Rigidbody.AddRelativeForce.html
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.
I currently have a method that checks to see if I go out of bounds either from either the top/bottom/sides. The object itself is a ball, and I have a question about getting the ball bouncing off the edges correctly? How do I go about this?
// The behavior is not quite what I want.
if ( InsideOfBounds )
{
Vector3 mCenter = Ball.getCenter();
Vector3 normalizeV = tempCenter;
normalizeV.Normalize();
mHeroBall.setVelocity(-testSpeed * normalizeV);
}
I can provide you with an example from a Breakout-clone written in XNA:
Ball.cs
Basically, you flip the right component of velocity to make a 'perfect' rebound. If you want, you can add friction or elasticity by multiplying by a coefficient like 0.95 or 1.1 so your ball speed change.
When you update the position of your object (ball), you want to check if the new value is out of bounds (and which bount Top\Bottom or Left\Right). If the it actually out of bounds, flip the correct element in your speed vector.
example: if the ball has passed the left bound then BallSpeed.X = -BallSpeed.X
don't forget to update the ball's position with the new speed and not the old at this point, or it will fly off the screen for the current frame (unless that isn't an issue).