How to jump and fall in Unity? - unity3d

I am coding a game jump in Unity. How can I jump (move) like in the Jupiter jump game, so that at a touch my hero will fall at high speed?
###
public float forceFly;
void Update () {
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce (new Vector2 (0, 1) forceFly);
if(Input.GetMouseButtonDown(0)){
// ?
}

This question is horribly structured, and it really looks like you didn't even try. What you'll need to do is get the current position of the object by its transform.
gameObject.transform.position
and apply vector math on it. In this case you're wanting to move the Y axis up (to move into the air). A very simple implementation of this would be like so:
gameObject.transform.position = new Vector3(transform.position.x, transform.position.y + forceFly, transform.position.z);
where forcefly is the amount that you'll "jump" every second.

Related

KnokBack of Player

I want a knock Back effect with this code but I dont know how.
I am new to coding still learning stuff !
This is my code where i want the KnockBack to have effect.
PlayerMovement.MyBody is a script with the rigidbody attached.
/// <summary>
/// If We CanDamage LifeScorecount minus 1 and stes CanDamage to false and starts Coroutine.
/// If Life is higher than 0 change thet text to the new life
/// If life is 0 then stop Time and start Coroutine RestartGame
/// </summary>
public void DealDamage()
{
if(CanDamage)
{
Anim.Play("Stun");
LifeScoreCount--;
Vector2 direction = (transform.position, 0);
PlayerMovement.myBody.AddForce(direction * -10f);
if (LifeScoreCount >= 0)
{
TextLife.text = "x" + LifeScoreCount;
}
if (LifeScoreCount == 0)
{
Time.timeScale = 0f;
StartCoroutine(RestartGame());
}
CanDamage = false;
StartCoroutine(WaitForDamage());
}
}
It depends on how you implemented your Movement and how you want your knock back to look like.
Assuming you simply want to push the rigidbody away, you can add a force like you already tried. To use a "one-time" push, you can use ForceMode.Impulse.
For the direction you want to use two points. The transform.position of the object, getting pushed away, subtracted by the transform.position of the object, which is pushing the character away.
So if you want an enemy to push away the player, you could try something like this:
Vector3 playerPosition = new Vector3(transform.position.x, 0, transform.position.z);
Vector3 enemyPosition = new Vector3(enemy.transform.position.x, 0, enemy.transform.position.z);
Vector3 knockbackDirection = (playerPosition - enemyPosition).normalized;
float power = 2f
rb.AddForce(knockbackDirection * power, ForceMode.Impulse);
If you also want the knockback to work along the y-axis, just use the Transform positions instead of the new Vector3.
If you don't have the reference to the enemy, you maybe want to add a parameter, so whenever an enemy damages the player, he will pass his own position as a parameter.
And maybe consider using a SerializeField for the knockback force, so you can easily edit it in the editor.

Detect collisions between 2 objects

I'm trying to do a little game on mobile using Unity and I've got a problem with the rotation of a maze.
To add context :
When your moving your finger on the screen, the maze is rotating on himself. There is a ball in it and you need to make it go on a cell to win the level.
When the maze is rotating too fast, the ball falls down and go through the ground and I don't know how to fix it.
I tried to play with the gravity, colliders...
This is the same when the ball is jumping (when the maze is going up and down quickly).
For the moment I just reset the ball position when you're falling.
{
ball.transform.position = new Vector3(0, 2, 0);
maze.transform.position = Vector3.zero;
maze.transform.rotation = Quaternion.identity;
}
Do you guys have some ideas ? Thanks
I had a similar problem in a tilt maze mini-game I worked on. Ideally implementing jkimishere's solution will work but I assume the maze is moving too fast for the collisions to register properly. You'll need to smooth the maze's rotation with a Lerp. In our case we had pressure plates with a tilt value, so it doesn't directly translate to your mobile use but perhaps give you a nudge in the right direction. We used:
public GameObject maze;
private float _lerpTime;
private bool _isRotating;
private Quaternion _startingRot, _desiredRot;
private void Awake()
{
_startingRot = maze.transform.localRotation;
}
private void Update()
{
//Don't want to move the maze if we don't ask for it
if(!_isRotating)
return;
//Lerp the maze's rotation
_lerpTime = Mathf.Clamp(_lerpTime + Time.deltaTime * 0.5f, 0f, 1f);
maze.transform.localRotation = Quaternion.Lerp(_startingRot, _desiredRot, _lerpTime);
//Once the maze gets where it needs to be, stop moving it
if(affectedObject.transform.localRotation.Equals(_desiredRot)
_isRotating = false;
}
private void ActivateTilt()
{
//Set the new starting point of the rotation.
_startingRot = maze.transform.localRotation;
//However you want to calculate the desired rotation here
//Reset our lerp and start rotating again
_lerpTime = 0f;
_isRotating = true;
}
This will ease the rotation of your maze over time. So that the ball can adapt to the new collider positions.
In the rigidbody(for the ball), make the collision detection to continuous, and in the rigidbody for the maze(if you have one) set the collision detection to continuous dynamic. Hope this helps!
I think that is unavoidable if you allow the player to move the platform freely. I suggest you restrain the speed at wich the player can tilt the platform. This way, the ball will have more frames to adapt to the new slope

Vector3.MoveTowards while also following cursor?

I'm making a character that follows my mouse position.
I also have enemies that are being instantiated and would like that character to move towards the location of the enemy but be a few feet higher than the enemy.
Since my character is a flying enemy I'm unsure how to use move towards in unity.
When my enemies are destroyed I would also like the character to continue following the cursor.
public class FollowCursor : MonoBehaviour
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(GameObject.FindWithTag("Enemy"))
{
transform.position = Vector3.MoveTowards.GameObject.FindWithTag("Enemy").transform.position;
}
else
{
transform.position = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x,Input.mousePosition.y,8.75f));
}
}
}
I understand you wish to move towards a flying enemy and/or have the flying enemy move towards your character.
I also understand that you wish to use the MoveTowards method to do this.
You should be able to do this by ignoring the Y position or setting it to a fixed value.
Like this.
//Method used: Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta);
//Set movespeed/steps
float speed = 5f;
float step = speed * Time.deltaTime;
//Define y position
float yourFixedYValue = 8.75f;
//Find target
Vector3 enemyPosition = GameObject.FindWithTag("Enemy").transform.position;
Vector3 target = new Vector3(enemyPosition.x, yourFixedYValue, enemyPosition.z);
//Move from current position towards target with step increment.
transform.position = Vector3.MoveTowards(transform.position, target, step);
Please elaborate what you mean if this didn't answer your question.
EDIT:
To move towards the mouse you could use a Raycast something like this inside your Update method.
if (Input.GetMouseButtonDown(0))
{ //If left mouse clicked
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Fire ray towards where mouse is clicked, from camera.
if (Physics.Raycast(ray, out hit)) //If hit something
target = hit.point; //point is a vector3 //hit.point becomes your target
}
That "something" can be any collider, also an enemy one. So can be used to move around in general and to move towards enemies.

Most correct way to move an object straight to hit a specific point of a huge Gameobject

The code could look something like this:
void Update () {
if(Vector3.Distance(transform.position, specificPositionOfHugeGameobject) < dist)
{
transform.position = Vector3.MoveTowards(transform.position,
specificPositionOfHugeGameobject, Time.deltaTime * speed);
}
}
Realise I do NOT want to move the object to hugeGameobject.position, but a specific point of that huge game object.
Best solution I have thought is creating an empty game object which is child of the huge game object. Then, move the object towards that empty child game object.
The solution you propose is the common way to do it in Unity.
As an alternative to go to a point, you could either hardcode it or let the user enter a Vector3 in a public field.
public Vector3 targetPosition;
void Update () {
if(Vector3.Distance(transform.position, specificPositionOfHugeGameobject) < dist)
{
transform.position = Vector3.MoveTowards(transform.position,
targetPosition, Time.deltaTime * speed);
}
}
This of course means that the target position is fixed. Since your huge game object is moving, the target point must be moving relatively to this. You could code yourself the computation of the targetPosition at each frame using the HugeGameObject's information (position and rotation). However this is exactly what Unity does for you when you parent objects: It computes the position of children elements regarding the parent.
So making use of Unity's hierarchy features is acctually the most correct way to do this.
Another simple way is add a simple Vector3 offset depend on Huge position:
public Vector3 offset;
void Update ()
{
if(Vector3.Distance(transform.position, specificPositionOfHugeGameobject) < dist)
{
transform.position = Vector3.MoveTowards(transform.position, hugePosition + offset, Time.deltaTime * speed);
}
}
Now play with offset in inspector.

visual lag of the moving picture in Unity3D. How to make it smoother?

I make a game in Unity3D (+2D ToolKit) for iOS.
It is 2d runner/platformer with side view. So on screen is moving background and obstacles. And we control up/down the main character to overcome obstacles.
The problem is that the moving picture has a visual lag. In other words, it moves jerkily or creates the tail area of the previous frames on iOS-devices. In XCode the number of frames is 30 and over.
I have objects 'plain' with the following script:
public class Move: Monobehavior
{
private float x;
public float Speed = 128.0f;
void Start()
{
x = transform.position.x;
}
void Update()
{
x += Time.DeltaTime *Speed;
Vector3 N = transform.position;
N.x = mathf.FloorInt(x);
transform.position = N;
}
}
The question is how to make the move of background smoother, without jerks and flicker on screen while playing? Maybe the problem is in framerate parameter.
Can anybody help me to find a solution?
I'd say it's the use of the FloorInt function which will move the background only in steps of 1 which is rather not smooth. It should get better when you comment that line out. Do you have any special reason why you are doing the FloorInt there?
The use of floor will definitely hurt your performance. Not only is it one more thing to calculate, but it is actually removing fidelity by removing decimals. This will definalty make the movement look 'jerky'. Also, update is not always called on the same time inteval, depending on what else is happening during that frame, so using Time.delaTime is highly recommended. Another thing, you do not need to set variables for x and Vector3 N, when you can update the transoms position like the code below. And if you have to, you sill only need to create one variable to update, and set your position to it. The code below just updates the players x position at a given rate, based on the amount of time that has passes since the last update. There should be no 'jerky' movement. (Unless you have a serious framerate drop);
public class Move: Monobehavior
{
public float Speed = 128.0f;
void Update()
{
transform.position =
(transform.position.x + (speed*Time.DeltaTime),
transform.position.y,
transform.position.z);
}
}