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

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

Related

How to make an object move endlessly?

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;
}
}
}

I can not play animation on AI, unity 2d

I tried to make a firefly for my game, which is an AI.I wanted it to make across the map, for that I watched a tutorial on YT from BlackThornProd, but when I tried animating it, and played the game, it was terrible, the animation were playing bizarre, like when the firefly needs to go on the right, the animations are playing like this; Left-Right-Idle-Right-etc.Im using Blend Tree.
How can I solve it?
Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCRandomMoveing : MonoBehaviour
{
public float speed;
public Transform[] moveSpots;
private int randomSpot;
private float waitTime;
public float startWaitTime;
public Animator anim;
Vector2 movement;
void Start()
{
waitTime = startWaitTime;
randomSpot = Random.Range(0, moveSpots.Length);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);
if(Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f){
if(waitTime <= 0){
randomSpot = Random.Range(0, moveSpots.Length);
waitTime = startWaitTime;
} else {
waitTime -= Time.deltaTime;
}
}
}
void FixedUpdate(){
anim.SetFloat("Horizontal", transform.position.x);
anim.SetFloat("Vertical", transform.position.y);
anim.SetFloat("Speed", transform.position.sqrMagnitude);
}
}
I think you move your fly and also try to animate its position right? Try maybe to just animate and dont change the transforms or even better rotate your fly with lookat vector and use animation controler to just adjust the speed of wings.
Try this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateTowardsSpline : MonoBehaviour
{
// put the points from unity interface
public List<Transform> wayPointList = new List<Transform>();
public int currentWayPoint = 0;
Transform targetWayPoint;
public float speed = 0f;
public float turningRate = 1f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
if (currentWayPoint < this.wayPointList.Count - 1)
{
if (targetWayPoint == null)
targetWayPoint = wayPointList[currentWayPoint];// hier put a random nr
RotateTowards();
}
}
void RotateTowards()
{
// rotate towards the target
transform.forward = Vector3.RotateTowards(transform.right, targetWayPoint.position - transform.position, 0.02f * (speed) * Time.deltaTime, 1.0f);
}
}

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

Quaternion lerping not working as expected in Unity with c#

I have tried my own methods but I have not been able to get a method that works, here is an example gif: https://gyazo.com/5cd4b74ee45240d3ff9ee13ae6ca6af6
And here is the code that is used in that gif:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
public GameObject moving;
float lerpTime = 5f;
float currentLerpTime;
float moveDistance = 10f;
Quaternion startPos;
Quaternion endPos;
protected void Start()
{
startPos = moving.transform.rotation;
endPos = new Quaternion(0, 0, 0, 0);
}
protected void Update()
{
//reset when we press spacebar
if (Input.GetKeyDown(KeyCode.Space))
{
currentLerpTime = 0f;
}
//increment timer once per frame
currentLerpTime += Time.deltaTime;
if (currentLerpTime > lerpTime)
{
currentLerpTime = lerpTime;
}
//lerp!
float perc = currentLerpTime / lerpTime;
print(perc);
moving.transform.rotation = Quaternion.Lerp(startPos, endPos, perc);
}
}
It does not change until it reaches alpha 1 and I'm not sure why.
If you have any clue why it's doing this and know how to help me please write a comment.

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