How to make an object move endlessly? - c#

I want to move an object from position A to position B on X axis endlessly. But it does move and comeback only once. How to make it continuosly? I've tried Vector3.Lerp or just creating new Vector3 but it only teleports.
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingTarget : MonoBehaviour
{
[SerializeField] private Vector3 firstPosition = new Vector3(-14f, 2.5f, 17f);
[SerializeField] private Vector3 secondPosition = new Vector3(14f, 2.5f, 17f);
public float speed = 10f;
void Start()
{
transform.position = firstPosition;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, secondPosition, Time.deltaTime * speed);
if(transform.position == secondPosition)
{
secondPosition = firstPosition;
}
}
}
`

As alternative you could also use Mathf.PingPong like e.g.
// By default afaik a full cycle takes 2 seconds so in order to normalize
// this to one second we will divide by this times 2 later
public float cycleDuration = 1;
private void Update ()
{
transform.position = Vector3.Lerp(firstPosition, secondPosition, Mathf.PingPong(Time.time / (cycleDuration * 2f), 1f));
}
In case your object is spawned later in the game you might want to rather always start at the first position and do
private float timer;
private void Update ()
{
transform.position = Vector3.Lerp(firstPosition, secondPosition, Mathf.PingPong(timer / (cycleDuration * 2f), 1f));
timer += Time.deltaTime;
}

I don't use Unity, but since nobody else answered....
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingTarget : MonoBehaviour
{
[SerializeField] private Vector3 firstPosition = new Vector3(-14f, 2.5f, 17f);
[SerializeField] private Vector3 secondPosition = new Vector3(14f, 2.5f, 17f);
private Vector3 target;
public float speed = 10f;
void Start()
{
transform.position = firstPosition;
target = secondPosition;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
if (transform.position == firstPosition)
{
target = secondPosition;
}
else if (transform.position == secondPosition)
{
target = firstPosition;
}
}
}

Related

Adding a delay to a moving object?

I have an object that moves forward and backwards. Just as it is about to move in the opposite direction, I am trying to add a very brief delay (1.0f) before it moves again.
public class PushPlayer : MonoBehaviour
{
public float moveAmount = 3.3f;
public float speed = 1.1f;
private Vector3 startPos;
void Start()
{
startPos = transform.position;
}
void Update()
{
Vector3 v = startPos;
v.z += moveAmount * Mathf.Sin(Time.time * speed);
transform.position = v;
}
}
I attempted to implement a coroutine in two different ways with one of them not working and the other making my entire game basically freeze. I tried to call the method again as well which I am not sure works at all however there were no results.
using System.Collections;
using UnityEngine;
public class PushPlayer : MonoBehaviour
{
public float moveAmount = 3.3f;
public float speed = 1.1f;
private Vector3 startPos;
[SerializeField] private float _delay = 1f;
void Start()
{
startPos = transform.position;
StartCoroutine(DoMoving());
}
private IEnumerator DoMoving()
{
while (true)
{
yield return DoCycle();
yield return new WaitForSeconds(_delay);
}
IEnumerator DoCycle()
{
var time = 0f;
while (time * speed < Mathf.PI * 2f)
{
Vector3 v = startPos;
v.z += moveAmount * Mathf.Sin(time * speed);
transform.position = v;
yield return null;
time += Time.deltaTime;
}
}
}
}
But it would be better to use dotween or dotween + unitask for async moving

How to randomly speed up my game object in unity 2D

Hey so I dont know how to implement a random speedup to my gameobject ive been stuck for a while if some would help me it would be very much appericated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hexagon : MonoBehaviour
{
public Rigidbody2D rb;
public float shrinkSpeed = 3f;
// Start is called before the first frame update
void Start()
{
rb.rotation = Random.Range(0f, 360f);
transform.localScale = Vector3.one * 10f;
}
// Update is called once per frame
void Update()
{
transform.localScale -= Vector3.one * shrinkSpeed * Time.deltaTime * 2;
if(transform.localScale.x <= .05f)
{
Destroy(gameObject);
}
}
}
private void RandomSpeedUp()
{
float minSpeedUp = 1.3f; //30% speed boost
float maxSpeedUp = 1.75f; //75% speed boos
rb.velocity*= Random.Range(minSpeedUp, maxSpeedUp);
}
This should be a good starting point

How can I move a cube between other targets in different ways between each one?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementSpeedController : MonoBehaviour
{
public Transform[] targets;
public float speed = 1f;
public Vector3 velocity = Vector3.zero;
private void Start()
{
}
private void Update()
{
transform.position = Vector3.Lerp(transform.position,
targets[0].position, speed * Time.deltaTime);
if (transform.position == targets[0].position)
{
transform.position = Vector3.MoveTowards(transform.position,
targets[1].position, speed * Time.deltaTime);
}
if (transform.position == targets[1].position)
{
transform.position = Vector3.SmoothDamp(transform.position,
targets[2].position, ref velocity, speed * Time.deltaTime);
}
}
}
The script is attached to a cube the cube should move between 3 other cubes each cube in another positions. and I want that the transform will move to the first target using lerp then movetowards and then to the last cube using smoothdamp to show all the movements.
The problem is how to do it without manually type each target index 0,1,2 ? and how to move it between them because now this is true :
transform.position == targets[0].position
but it's not moving to the next cube.
Tried this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementSpeedController : MonoBehaviour
{
public Transform[] targets;
public float speed = 1f;
public Vector3 velocity = Vector3.zero;
private int targetIndex = 0;
private void Start()
{
}
private void Update()
{
var targetPosition = targets[targetIndex];
if (targetIndex == 0)
{
transform.position = Vector3.Lerp(transform.position,
targetPosition.position, speed * Time.deltaTime);
}
if(transform.position == targetPosition.position)
{
targetIndex++;
transform.position = Vector3.MoveTowards(transform.position,
targets[1].position, speed * Time.deltaTime);
}
}
}
Add a variable for targetIndex, initialize it to zero, and each time you reach the target increase that index. Use that index in your targets array.
targetPosition = targets[targetIndex];
You can also use that index to figure out which movement type you need to use.
if (targetIndex == 0) // do lerp or in a switch case
Here is an example.
private Vector3 startingPosition = Vector3.zero;
private int targetIndex = 0;
private float lerpT = 0;
void Start()
{
targetIndex = -1;
SetNextTarget();
}
void Update()
{
switch (targetIndex)
{
case 0: UpdateLerp(); break;
case 1: UpdateMoveTowards(); break;
case 2: UpdateSmoothDamp(); break;
}
}
void UpdateLerp()
{
lerpT += Time.deltaTime * speed;
if (lerpT > 1)
lerpT = 1;
transform.position = Vector3.Lerp(startingPosition, target, lerpT);
if (lerpT == 1)
{
SetNextTarget();
}
}
void UpdateMoveTowards()
{
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target) <= Mathf.Epsilon)
{
SetNextTarget();
}
}
void UpdateSmoothDamp()
{
// Using the examples, fill in this one with the smooth damp version of movement
}
void SetNextTarget()
{
targetIndex++;
target = targets[targetIndex];
startingPosition = transform.position;
}

How To randomize timer duration between two floats

Currently, This code spawns my prefab with only 1 float aka 1 second or w.e. I'm wanting to spawn my prefab between a minimum float and maximum float but not sure what to do because I'm novice and still learning c# and unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Spawn : MonoBehaviour
{
[SerializeField]
public GameObject coin;
[SerializeField]
float fTimeIntervals;
[SerializeField]
Vector2 v2SpawnPosJitter;
float fTimer = 0;
public CurrencyManager cm;
// Start is called before the first frame update
void Start()
{
fTimer = fTimeIntervals;
}
// Update is called once per frame
void Update()
{
fTimer -= Time.deltaTime;
if (fTimer <= 0)
{
fTimer = fTimeIntervals;
Vector2 v2SpawnPos = transform.position;
v2SpawnPos += Vector2.right * v2SpawnPosJitter.x * (Random.value - 0.5f);
v2SpawnPos += Vector2.up * v2SpawnPosJitter.y * (Random.value - 0.5f);
GameObject cmscript = Instantiate(coin, v2SpawnPos, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
cmscript.GetComponent<AutoDestroy>().CM = cm;
}
}
}
Split your fTimeIntervals field into a fMaxTimeInterval field and a fMinTimeInterval field then use Random.Range when you reset the timer to set it to a value between those intervals. You can even make a ResetTimer method to do this in Start and Update so if you change how you do it, you only have to change it in one place:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Spawn : MonoBehaviour
{
[SerializeField]
public GameObject coin;
[SerializeField]
float fMinTimeInterval;
[SerializeField]
float fMaxTimeInterval;
[SerializeField]
Vector2 v2SpawnPosJitter;
float fTimer = 0;
public CurrencyManager cm;
// Start is called before the first frame update
void Start()
{
ResetTimer();
}
// Update is called once per frame
void Update()
{
fTimer -= Time.deltaTime;
if (fTimer <= 0)
{
ResetTimer();
Vector2 v2SpawnPos = transform.position;
v2SpawnPos += Vector2.right * v2SpawnPosJitter.x * (Random.value - 0.5f);
v2SpawnPos += Vector2.up * v2SpawnPosJitter.y * (Random.value - 0.5f);
GameObject cmscript = Instantiate(coin, v2SpawnPos, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
cmscript.GetComponent<AutoDestroy>().CM = cm;
}
}
void ResetTimer()
{
fTimer = Random.Range(fMinTimeInterval,fMaxTimeInterval);
}
}
Didn't really understand what you meant, did you mean the timer?
Use random.range if you want a random number between min/max value
https://docs.unity3d.com/ScriptReference/Random.Range.html

How can I add simple up/down movement on the Y-axis to an enemy that has velocity on the X-axis attached to it?

I'm creating a 2D horizontal side-scroller and I have enemies being spawned whose rigidbody component is being used to give them a velocity like so:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour
{
public float speed;
public new Rigidbody2D rigidbody;
public bool random;
void Start()
{
if (random) {
rigidbody.velocity = Random.value * transform.right * speed;
}
else
{
rigidbody.velocity = transform.right * speed;
}
}
}
How can I have these enemies also move up and down constantly on the the Y-axis while they are moving with a velocity on the X-axis? Everything I have tried seems to interfere with the velocity of the objects. I am basically trying to create a simple behavioral pattern so as to make the targets harder for the player to aim at.
Any ideas?
This is just a starting point, but you would have to experiment with different ways to do it to get the behavior you want. Maybe you can try using rigidbody.AddForce too.
If you haven't already, I recommend watching the video tutorials for the 2D platformer.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Mover : MonoBehaviour {
public float speed, waveSpeed;
new Rigidbody2D rigidbody;
public bool random;
// Use this for initialization
void Start () {
rigidbody = GetComponent<Rigidbody2D>();
if (random) {
rigidbody.velocity = Random.value * transform.right * speed;
} else {
rigidbody.velocity = transform.right * speed;
}
}
float angle = 0;
// Use this for physics calculations
void FixedUpdate () {
var wave = Mathf.Sin(angle += waveSpeed); // goes from -1 to +1
var p = rigidbody.position;
p.y = wave; // or: yCenter + yHeight * wave
rigidbody.position = p;
}
}
I have found the solution by following the answer given under this link: https://gamedev.stackexchange.com/questions/96878/how-to-animate-objects-with-bobbing-up-and-down-motion-in-unity?newreg=ccb2eaf1b725413ca777a68348637990
Here is my updated code:
public class EnemyMover : MonoBehaviour {
public float speed;
public new Rigidbody2D rigidbody;
public bool random;
float originalY;
public float floatStrength = 1;
void Start()
{
this.originalY = this.transform.position.y;
if (random) {
rigidbody.velocity = Random.value * transform.right * speed;
}else
{
rigidbody.velocity = transform.right * speed;
}
}
void Update()
{
transform.position = new Vector3(transform.position.x,
originalY + ((float)System.Math.Sin(Time.time) * floatStrength),
transform.position.z);
}
}

Categories

Resources