Unity - Quaternion.Slerp instantly rotating - c#

I am trying to have my object smoothly rotate on the Z axis from 0 to 180, back and forth on every button press.
The Quaternion.Slerp setup i'm using does not smoothly rotate to the target rotation, rather it instantly jumps to a number close to it. After many button presses that call the Quaternion.Slerp, it it finally halfs works in that it goes from 0 to 180, but still instantly and not smoothly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public bool movePlayer;
private float maxMoveSpeed;
public float waitToMove;
Rigidbody2D thisRigidbody;
//SCOOP variables
private GameObject scoop;
private GameObject scoopRotation;
Quaternion currentScoopRotation;
public Quaternion targetScoopRotation;
Quaternion lastScoopRotation;
public float scoopRotateTime;
// Use this for initialization
void Start ()
{
thisRigidbody = gameObject.GetComponent<Rigidbody2D> ();
maxMoveSpeed = moveSpeed;
//SCOOP finders
scoop = GameObject.FindGameObjectWithTag ("Scoop");
currentScoopRotation = scoop.transform.rotation;
}
// Update is called once per frame
void Update ()
{
if(movePlayer)
thisRigidbody.velocity = new Vector2 (moveSpeed, thisRigidbody.velocity.y);
//Rotates SCOOP using Quaternions + Spacebar
if (Input.GetKeyDown(KeyCode.Space)) {
lastScoopRotation = currentScoopRotation;
scoop.transform.transform.rotation = Quaternion.Lerp (currentScoopRotation, targetScoopRotation, scoopRotateTime * Time.time);
currentScoopRotation = targetScoopRotation;
targetScoopRotation = lastScoopRotation;
changeMoveDirection ();
}
}
void changeMoveDirection()
{
moveSpeed *= -1;
}
IEnumerator changeDirectionCO()
{
//thisRigidbody.velocity = new Vector2 (0f,0f);
//moveSpeed = 0;
yield return new WaitForSeconds (waitToMove);
moveSpeed *= -1;
}
}

Related

In Unity player movement speed is not being added to the first bullet fired

I'm trying to make a 2D top-down shooter in Unity. I want it so when the you hold down the left mouse button the player fires a series of bullets until you run out of ammo. The player's movement speed is slowed while firing and the players movement speed should be added to the bullet's movement speed. For some reason the players movement speed is only applied to the bullets AFTER the first bullet is fired. The first bullet always seems to keep the slightly faster 'sprint' movement speed.
Weapon script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
private GameObject bulletPrefab;
private Transform firePoint;
private PlayerControls player;
public float fireForce = 10f;
private bool cooldown = false;
private int bullets;
public int bulletDamage;
public int maxAmmo;
public float fireRate = 0.5f;
public float reloadRate = 2.5f;
public bool noAmmo = false;
public float walkSpeed = 2f;
private float timeSinceLastShot = 0f;
void Update()
{
// increase time since last shot
timeSinceLastShot += Time.deltaTime;
// if left-click is held down
if (Input.GetMouseButton(0))
{
// if enough time has passed since last shot
if (timeSinceLastShot >= fireRate && noAmmo == false)
{
player.moveSpeed = walkSpeed;
bullets -= 1;
cooldown = true;
if (bullets <= 0)
{
noAmmo = true;
player.moveSpeed = player.baseSpeed;
}
// instantiate a bullet
GameObject bullet = Instantiate(bulletPrefab, firePoint.transform.position, Quaternion.identity);
bullet.GetComponent<Bullet>().bulletDamage = bulletDamage;
// add player movement speed to bullet's speed
bullet.GetComponent<Rigidbody2D>().velocity = player.GetComponent<Rigidbody2D>().velocity;
bullet.GetComponent<Rigidbody2D>().AddForce(transform.up * fireForce, ForceMode2D.Impulse);
// reset time since last shot
timeSinceLastShot = 0f;
}
}
// if left-click is not held down
else
{
cooldown = false;
// restore player movement speed
player.moveSpeed = player.baseSpeed;
}
}
public void FillMag()
{
bullets = maxAmmo;
noAmmo = false;
}
}
PlayerControls:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
public float moveSpeed = 5f;
public float baseSpeed = 5f;
public int health;
public Weapon weapon;
private Rigidbody2D rb;
Vector2 mousePosition;
Vector2 moveDirection;
public float walkSpeed = 2f;
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY).normalized;
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
Vector2 aimDirection = mousePosition - rb.position;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 90f;
rb.rotation = aimAngle;
}
}
The player is moving from left to right.
Player firing
According to Unity's lifecycle, inputs are only calculated just before the Update method is called, but physics are applied during the FixedUpdate method. Is this what is causing my problems? I've tried moving some calculations into FixedUpdate and LateUpdate but nothing seems to make any difference.
Any help is appreciated. I've been banging my head against this for a few days now. I'm an amature, so feel free to explain like I'm 5.
So there are 2 problems with your code:
if you are not holding down left mouse, but multiple click instead:
the else statement in the Update() will immediately set it player back to base speed, which is not really matter if you intent to holding your mouse.
There are 2 concurrent things happen
first, you set player moveSpeed in Weapon Update()
at the same time, you calculate player velocity in Player Update()
But it TAKES TIME for player to update velocity before you get it right to your weapon.
Therefore, I recommend you to use IEnumerator to delay the fire action.
public class Weapon : MonoBehaviour
{
void FixedUpdate()
{
// increase time since last shot
timeSinceLastShot += Time.deltaTime;
// if left-click is held down
if (Input.GetMouseButton(0))
{
// if enough time has passed since last shot
if (timeSinceLastShot >= fireRate && noAmmo == false)
{
//player.moveSpeed = walkSpeed;
StopAllCoroutines();
StartCoroutine(SetSpeed());
bullets -= 1;
cooldown = true;
if (bullets <= 0)
{
noAmmo = true;
player.moveSpeed = player.baseSpeed;
}
// instantiate a bullet
StartCoroutine(FireBulelt());
// reset time since last shot
timeSinceLastShot = 0f;
}
}
// if left-click is not held down
}
IEnumerator SetSpeed()
{
player.moveSpeed = walkSpeed;
yield return new WaitForSeconds(0.5f);
cooldown = false;
// restore player movement speed
player.moveSpeed = player.baseSpeed;
yield return null;
}
IEnumerator FireBulelt()
{
yield return new WaitForSeconds(0.05f);
GameObject bullet = Instantiate(bulletPrefab, player.transform.position, Quaternion.identity);
print(" player.GetComponent<Rigidbody2D>().velocit " + player.GetComponent<Rigidbody2D>().velocity);
// add player movement speed to bullet's speed
Rigidbody2D bulletRB = bullet.GetComponent<Rigidbody2D>();
print(" bulletRB.velocit " + bulletRB.velocity);
bulletRB.velocity = player.GetComponent<Rigidbody2D>().velocity;
print(" after bulletRB.velocit " + bulletRB.velocity);
bulletRB.AddForce(transform.up * fireForce, ForceMode2D.Impulse);
}
}
And you should add print() like I did to keep track of code behavior when you're debugging.

How to slow character down when moving into a specific area(tilemap?)

Here is my script to make the character move
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
Vector3 moveDelta;
BoxCollider2D boxCollider;
protected float speed = 2f;
// Start is called before the first frame update
void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
moveDelta = new Vector3(x,y,0);
if(moveDelta.x<0)
{
transform.localScale = new Vector3(-1,1,1);
}
else if(moveDelta.x>0)
{
transform.localScale = Vector3.one;
}
transform.Translate(moveDelta*Time.deltaTime*speed);
}
}
I draw a tilemap like this,and I want that when character moves into this area,the speed will be slowed down
Here's the image
How can I do about this?

Why the object is not rotating towards the other object?

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Characters.ThirdPerson;
public class DistanceCheck : MonoBehaviour
{
public Transform target;
public float lerpDuration;
public float rotationSpeed;
public GameObject descriptionTextImage;
public TextMeshProUGUI text;
public ThirdPersonUserControl thirdPersonusercontrol;
private Animator anim;
private float timeElapsed = 0;
private float startValue = 1;
private float endValue = 0;
private float valueToLerp = 0;
private bool startRot = false;
// Start is called before the first frame update
void Start()
{
anim = transform.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(startRot)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation,
target.rotation, rotationSpeed * Time.deltaTime);
}
}
private void OnTriggerExit(Collider other)
{
if (other.name == "Colliding Area")
{
StartCoroutine(SlowDown());
}
}
IEnumerator SlowDown()
{
while (timeElapsed < lerpDuration)
{
valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
anim.SetFloat("Forward", valueToLerp);
timeElapsed += Time.deltaTime;
yield return null;
}
thirdPersonusercontrol.enabled = false;
descriptionTextImage.SetActive(true);
yield return new WaitForSeconds(3f);
startRot = true;
}
}
I used a breakpoint and when startRot is true it does getting to the Quaternion.RotateTowards line in the Update and the rotationSpeed is 5 but the transform is not rotating at all.
I want that the transform will rotate by 180 degrees or what even angle the transform is looking at forward it should rotate back towards the target.
The transform and the target both facing same direction and still the transform is not rotating at all towards the target.
If i'm changing on my own the transform rotation at runtime it will rotate but when it's getting to the Update it's not rotating at all.
Quaternion.RotateTowards will change one rotation towards another one, if two objects are facing same direction, they have same rotation, so nothing will be changed.
If you want the object to face the target, you need use a rotation created by Quaternion.LookRotation.
transform.rotation = Quaternion.RotateTowards(transform.rotation,
Quaternion.LookRotation(target.position - transform.position),
rotationSpeed * Time.deltaTime);

How can I add a rotation to my bullets when they are shot?

I haven't used rotation in a while so I can't remember how to do this. I am trying to make a random trajectory for my bullets and I want to add a random rotation but I don't know how to add the rotation. I commented in the script where the rotation should be added. I have tried adding + transform.rotation * Quaternion.Euler(0,rot, 0) but I got the error error CS0019: Operator '+' cannot be applied to operands of type 'Vector3' and 'Quaternion'. What could I add to make this work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Player : MonoBehaviour
{
public GameObject bulletPrefab;
public Camera playerCamera;
private Coroutine hasCourutineRunYet = null;
public int ammo = 300;
public Text Ammmo;
private float xPos;
private float zPos;
private float yPos;
private float rot;
// Update is called once per frame
void Update()
{
Ammmo.text = "Ammo: " + ammo.ToString();
if(Input.GetMouseButtonDown(0))
{
if (hasCourutineRunYet == null)
hasCourutineRunYet = StartCoroutine(BulletShot());
}
}
IEnumerator BulletShot()
{
xPos = Random.Range(-0.3f, 0.3f);
yPos = Random.Range(-0.3f, 0.3f);
zPos = Random.Range(-0.3f, 0.3f);
rot = Random.Range(-10.0f, 10.0f);
GameObject bulletObject = Instantiate(bulletPrefab);
bulletObject.transform.position = playerCamera.transform.position + playerCamera.transform.forward + new Vector3(xPos, yPos, zPos) ; // add rotation here
bulletObject.transform.forward = playerCamera.transform.forward;
yield return new WaitForSeconds(1.0f);
hasCourutineRunYet = null;
ammo--;
}
}
I would look into the transform.rotation.RotateAround function. With this, you can call your bullet's relative forward, and rotate around itself essentially
Code Below:
using UnityEngine;
//Attach this script to a GameObject to rotate around the target position.
public class Example : MonoBehaviour
{
//Assign a GameObject in the Inspector to rotate around
public GameObject target;
void Update()
{
// Spin the object around the target at 20 degrees/second.
transform.RotateAround(target.transform.position, Vector3.up, 20 * Time.deltaTime);
}
}
Here's a URL to the documentation: https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html

Print Unity Coordinates to a string at specified time interval

I want to move a cube using some device and periodically (every 3 seconds) print those coordinates to a file. I am not sure how to accomplish this with my code below. Does anybody have ideas as to how this can be done?
Thank you!
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
[RequireComponent(typeof(MeshCollider))]
public class UserController : MonoBehaviour {
public int speed = 20;
// Update is called once per frame
void Update()
{
// get input data from keyboard or controller
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// update player position based on input
Vector3 position = transform.position;
position.x += moveHorizontal * speed * Time.deltaTime;
position.z += moveVertical * speed * Time.deltaTime;
transform.position = position;
}
void OnMouseDrag()
{
if(Input.GetMouseButton(0))
{
float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
}
}
}
I would suggest creating a separate script and attach it to your cube.
public class CubeTracker : MonoBehaviour
{
private bool logging = true;
void Awake()
{
StartCoroutine(LogPosition());
}
private IEnumerator LogPosition()
{
while (logging)
{
Debug.Log(transform.position);
yield return new WaitForSeconds(3f);
}
}
}
This will start a coroutine as soon as the cube is created and should log your desired result into console. If that's what you desire, you can then go ahead and replace the Debug.Log with a write-to-file implementation.
Use a global variable, and feed it inside Update() method.
for example:
private Vector3 LastCoordinate{get; set;}
and the use a periodic timer like :
private System.Threading.Timer timer;
timer = new System.Threading.Timer(GetLastCoordinate, null, 3000, 0);
private void GetLastCoordinate()
{
lock(this)
{
Vector3 lastCoordEachThreeSecs = LastCoordinate;
}
}

Categories