How to reset z position to 0 when it reaches an end? - c#

I made my object move in one direction and reset z position to 0 when it reaches position 10. But position z does not returning to 0 when it reaches 10.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class NewBehaviourScript : MonoBehaviour
{
float z = 1.0F;
void Update()
{
if (z < 10.0f)
{
//move object forward
transform.Translate(0,0,z * Time.deltaTime * 0.5F);
}
else
{
z = 0;
}
}
}

The issue is that .Translate method moves an object by a specific vector. It doesn't assign a set position.
If you want to reset z position of a transform, assign a new vector to .position property containing the original x and y values and a 0 as the last parameter.
Here's a fixed up version of your code:
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private const float Speed = 1.0f;
private void Update()
{
if (transform.position.z < 10.0f)
{
// Moving object forward
transform.Translate(0, 0, Speed * Time.deltaTime);
}
else
{
transform.position = new Vector3(
transform.position.x,
transform.position.y,
0f);
}
}
}

Related

How To Rotate Objects Using C# Script In Unity2d?

So I'm Trying To Rotate My Coin Object to 0z if Y is above 0.17f and if its not will rotate back to 90z , the first if statement works fine but the other one keeps rotating my coin and i don't know why...? I'm Completely New To Unity and C# Lang !
Anyway Here's my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinScript : MonoBehaviour
{
public GameObject coin;
bool isRotated = false;
// Update is called once per frame
void FixedUpdate()
{
if (coin.transform.position.y > 0.17f && coin.transform.rotation.z >= 0f && !isRotated)
{
coin.transform.Rotate(coin.transform.rotation.x,coin.transform.rotation.y,-1f );
if (coin.transform.rotation.z <= 0f)
{
isRotated = true;
}
}else if (coin.transform.position.y < 0.17f && coin.transform.rotation.z <= 90f && isRotated)
{
coin.transform.Rotate(coin.transform.rotation.x,coin.transform.rotation.y,1f);
if (coin.transform.rotation.z >= 90f)
{
isRotated = false;
}
}
}
}
Transform.rotation is a Quaternion!
As the name suggests a Quaternion (also see Wikipedia -> Quaternion has not three but four components x, y, z and w. All these move within the range -1 to +1. Unless you really know exactly what you are doing you never touch these components directly.
If I understand you correctly you rather want to do something like e.g.
public class CoinScript : MonoBehaviour
{
public Transform coin;
public float anglePerSecond = 90;
private void FixedUpdate()
{
var targetRotation = coin.position.y > 0.17f ? Quaternion.identity : Quaternion.Euler(0, 0, 90);
coin.rotation = Quaternion.RotateTowards(coin.rotation, targetRotation, anglePerSecond * Time.deltaTime);
}
}

unity c# issue unable to get perfect position of a enemy in unity c# script using transform.position

when I command or set an enemy to go left and then at reaching a particular state or position i say my enemy to go right but it is not going right and not reaching to perfect position here is the code I think there is no issue in the code but it is not working properly so here are some images of the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enem : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = transform.position + new Vector3(-3f, 0f, 0f)* 1 * Time.deltaTime;
if (transform.position.x > -29)
{
transform.position = transform.position + new Vector3(3f, 0f, 0f) * 1 * Time.deltaTime;
}
}
}
Before adding any bool logic, try first simply moving your element:
using UnityEngine;
public class SimeMoveMove : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
transform.position += new Vector3(3f, 0f, 0f);
}
}
}
I smiled a little the moment I understood what you were trying to do.
I wrote the code imagining the result you were trying to make!
Create a cube, attach this code as component, and run the game.
// Gift for you friend
public class MoveTest : MonoBehaviour
{
private int _direction = 1;
void Start()
{
transform.position = Vector3.zero;
}
void Update()
{
Vector3 position = transform.position;
int direction = ShouldWeSwitchDirection(position.x, 0f);
if (direction != 0)
{
_direction = direction;
}
transform.position += _direction * new Vector3(3f, 0f, 0f) * 3f * Time.deltaTime;
}
private int ShouldWeSwitchDirection(float value, float center = 0f)
{
float direction = Mathf.Sign(value - center);
float distance = Mathf.Abs(value - center);
// If X Position is larger than 29
if (Mathf.Abs(distance) > 29)
{
// If X is on right side
if (direction >= 0)
{
return -1;
}
// If X is on left side.
else
{
return 1;
}
}
else
{
return 0;
}
}
}

Moving Maincamera slowly to another position

I want to move main camera slowly from one point to another point when a button is pressed. This button calls the method which has the code to move the camera.
I have tried using the Lerp method but the camera position is changing so fast that when I click on the button camera directly shifting to a new position. I want the camera to move slowly to a new position.
Below is my code, can anyone please help me with this.
=========================================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
public GameObject cam;
Vector3 moveToPosition;// This is where the camera will move after the start
float speed = 2f; // this is the speed at which the camera moves
public void move()
{
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
float step = speed * Time.deltaTime;
cam.transform.position = Vector3.Lerp(cam.transform.position, moveToPosition, step);
cam.transform.position = moveToPosition;
}
}
It's easier to use lerp with frames and you need to use it in an Update function. Try using the example from the Unity docs:
public int interpolationFramesCount = 45; // Number of frames to completely interpolate between the 2 positions
int elapsedFrames = 0;
void Update()
{
float interpolationRatio = (float)elapsedFrames / interpolationFramesCount;
Vector3 interpolatedPosition = Vector3.Lerp(Vector3.up, Vector3.forward, interpolationRatio);
elapsedFrames = (elapsedFrames + 1) % (interpolationFramesCount + 1); // reset elapsedFrames to zero after it reached (interpolationFramesCount + 1)
Debug.DrawLine(Vector3.zero, Vector3.up, Color.green);
Debug.DrawLine(Vector3.zero, Vector3.forward, Color.blue);
Debug.DrawLine(Vector3.zero, interpolatedPosition, Color.yellow);
}
Try using smooth damp.
Here is the new code you should try:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cameramove : MonoBehaviour
{
Vector3 matric;
public GameObject cam;
Vector3 moveToPosition;
float speed = 2f;
bool move_ = false;
void Update(){
if(move_){
//Assigning new position to moveTOPosition
moveToPosition = new Vector3(200f, 400f, -220f);
cam.transform.position =
Vector3.SmoothDamp(cam.transform.position,
moveToPosition,
ref matric, speed);
}
}
public void move()
{
move_ = true;
}
}

How can I add the float to the position on Y?

The original code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FloatInAir : MonoBehaviour
{
public float amplitude; //Set in Inspector
public float speed; //Set in Inspector
private float tempVal;
private Vector3 tempPos;
void Start ()
{
tempVal = transform.position.y;
}
void Update ()
{
tempPos.y = tempVal + amplitude * Mathf.Sin(speed * Time.time);
transform.position = tempPos;
}
}
But I want to keep the original position just changing the Y so I tried to change the transform.position line to :
transform.position = new Vector3(transform.position.x, transform.position.y + tempPos, transform.position.z);
But doing plus is wrong.
Use transform.localPosition instead of transform.position.
transform.localPosition will give the position of the transform relative to the parent transform.
Also You are assigning y position to tempPos.yso you should be adding tempPos.y and not tempPos.

Enemy movement just on some portion of ground 2D Unity

Can I make my enemy move just on some suspended blocks? I have a script but my enemy fall of them and doesn't stop when is not any block around . I am bound to put blocks higher just to stop his fall?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private float latestDirectionChangeTime;
private readonly float directionChangeTime = 3f;
private float characterVelocity = 2f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
void Start()
{
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
void calcuateNewMovementVector()
{
//create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
void Update()
{
//if the changeTime was reached, calculate a new movement vector
if (Time.time - latestDirectionChangeTime > directionChangeTime)
{
latestDirectionChangeTime = Time.time;
calcuateNewMovementVector();
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
}
}

Categories