I have been trying to make this work for a while and I am failing.
I have a Rigidbody2D in a top down 2D level and I am trying to simply move it along the coordinates (the levels are gridlike) so one step / button press equals exactly one square walked. It should only be possible to walk in one of the four directions, and no matter when the user stops the walking motion, it should end on a square. A good game equivalent of what I want to achieve is the lufia / breath of fire / any similar RPG series. I've tried using coroutines to get the update function to wait one second after every step, but that does not seem to work. The closest I've come to is the code down below. Thanks guys!
public class PlayerMovement2D : MonoBehaviour
{
Rigidbody2D rbody;
Animator anim;
float speed = 1.25f;
Vector2 pos;
void Start()
{
rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
pos = rbody.position;
}
void FixedUpdate()
{
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector.x != 0 || movement_vector.y != 0)
{
if (movement_vector.x > 0)
{
pos += Vector2.right;
pos.y = 0;
}
else if (movement_vector.x < 0)
{
pos += Vector2.left;
pos.y = 0;
}
else if (movement_vector.y > 0)
{
pos += Vector2.up;
pos.x = 0;
}
else if (movement_vector.y < 0)
{
pos += Vector2.down;
pos.x = 0;
}
anim.SetBool("IsWalking", true);
anim.SetFloat("Input_x", movement_vector.x);
anim.SetFloat("Input_y", movement_vector.y);
}
else
{
anim.SetBool("IsWalking", false);
}
rbody.position = Vector2.MoveTowards(rbody.position, pos, speed * Time.deltaTime);
//transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
pos = rbody.position;
}
}
I think what you try to program is similar to the RogueLike game that is part of the tutorial collection in Unity website. Check first the intro video to confirm that is what you are planning to achieve
https://unity3d.com/es/learn/tutorials/projects/2d-roguelike-tutorial/project-introduction?playlist=17150
If so, this is how they handle it:
using UnityEngine;
using System.Collections;
//The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
public abstract class MovingObject : MonoBehaviour
{
public float moveTime = 0.1f; //Time it will take object to move, in seconds.
public LayerMask blockingLayer; //Layer on which collision will be checked.
private BoxCollider2D boxCollider; //The BoxCollider2D component attached to this object.
private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object.
private float inverseMoveTime; //Used to make movement more efficient.
//Protected, virtual functions can be overridden by inheriting classes.
protected virtual void Start ()
{
//Get a component reference to this object's BoxCollider2D
boxCollider = GetComponent <BoxCollider2D> ();
//Get a component reference to this object's Rigidbody2D
rb2D = GetComponent <Rigidbody2D> ();
//By storing the reciprocal of the move time we can use it by multiplying instead of dividing, this is more efficient.
inverseMoveTime = 1f / moveTime;
}
//Move returns true if it is able to move and false if not.
//Move takes parameters for x direction, y direction and a RaycastHit2D to check collision.
protected bool Move (int xDir, int yDir, out RaycastHit2D hit)
{
//Store start position to move from, based on objects current transform position.
Vector2 start = transform.position;
// Calculate end position based on the direction parameters passed in when calling Move.
Vector2 end = start + new Vector2 (xDir, yDir);
//Disable the boxCollider so that linecast doesn't hit this object's own collider.
boxCollider.enabled = false;
//Cast a line from start point to end point checking collision on blockingLayer.
hit = Physics2D.Linecast (start, end, blockingLayer);
//Re-enable boxCollider after linecast
boxCollider.enabled = true;
//Check if anything was hit
if(hit.transform == null)
{
//If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
StartCoroutine (SmoothMovement (end));
//Return true to say that Move was successful
return true;
}
//If something was hit, return false, Move was unsuccesful.
return false;
}
//Co-routine for moving units from one space to next, takes a parameter end to specify where to move to.
protected IEnumerator SmoothMovement (Vector3 end)
{
//Calculate the remaining distance to move based on the square magnitude of the difference between current position and end parameter.
//Square magnitude is used instead of magnitude because it's computationally cheaper.
float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
//While that distance is greater than a very small amount (Epsilon, almost zero):
while(sqrRemainingDistance > float.Epsilon)
{
//Find a new position proportionally closer to the end, based on the moveTime
Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
//Call MovePosition on attached Rigidbody2D and move it to the calculated position.
rb2D.MovePosition (newPostion);
//Recalculate the remaining distance after moving.
sqrRemainingDistance = (transform.position - end).sqrMagnitude;
//Return and loop until sqrRemainingDistance is close enough to zero to end the function
yield return null;
}
}
//The virtual keyword means AttemptMove can be overridden by inheriting classes using the override keyword.
//AttemptMove takes a generic parameter T to specify the type of component we expect our unit to interact with if blocked (Player for Enemies, Wall for Player).
protected virtual void AttemptMove <T> (int xDir, int yDir)
where T : Component
{
//Hit will store whatever our linecast hits when Move is called.
RaycastHit2D hit;
//Set canMove to true if Move was successful, false if failed.
bool canMove = Move (xDir, yDir, out hit);
//Check if nothing was hit by linecast
if(hit.transform == null)
//If nothing was hit, return and don't execute further code.
return;
//Get a component reference to the component of type T attached to the object that was hit
T hitComponent = hit.transform.GetComponent <T> ();
//If canMove is false and hitComponent is not equal to null, meaning MovingObject is blocked and has hit something it can interact with.
if(!canMove && hitComponent != null)
//Call the OnCantMove function and pass it hitComponent as a parameter.
OnCantMove (hitComponent);
}
//The abstract modifier indicates that the thing being modified has a missing or incomplete implementation.
//OnCantMove will be overriden by functions in the inheriting classes.
protected abstract void OnCantMove <T> (T component)
where T : Component;
}
Link to this part of the tutorial:
https://unity3d.com/es/learn/tutorials/projects/2d-roguelike-tutorial/moving-object-script?playlist=17150
You can use Vector2.Lerp method in combination of Unity's Coroutine system.
public class Movement
: MonoBehaviour
{
IEnumerator m_MoveCoroutine;
float m_SpeedFactor;
void Update()
{
// if character is already moving, just return
if ( m_MoveCoroutine != null )
return;
// placeholder for the direction
Vector2 direction; // between { -1, -1 } and { 1, 1 }
// calculate your direction based on the input
// and set that direction to the direction variable
// eg. direction = new Vector2(Input.GetAxisRaw("Horizontal") > 0 ? 1 : -1,...)
// then check if direction is not { 0, 0 }
if( direction != Vector2.zero )
{
// start moving your character
m_MoveCoroutine = Move(direction);
StartCoroutine(m_MoveCoroutine);
}
}
IEnumerator Move(Vector2 direction)
{
// Lerp(Vector2 a, Vector2 b, float t);
Vector2 orgPos = transform.Position; // original position
Vector2 newPos = orgPos + direction; // new position after move is done
float t = 0; // placeholder to check if we're on the right spot
while( t < 1.0f ) // loop while player is not in the right spot
{
// calculate and set new position based on the deltaTime's value
transform.position = Vector2.Lerp(orgPos, newPos, (t += Time.deltaTime * m_SpeedFactor));
// wait for new frame
yield return new WaitForEndFrame();
}
// stop coroutine
StopCoroutine(m_MoveCoroutine);
// get rid of the reference to enable further movements
m_MoveCoroutine = null;
}
}
This method assumes that you can move in the specified direction. But you still should check if your new position is "walkable" before starting the Move Coroutine.
I think you want to do the movement in a coroutine that, while it is active, disabled further movement until it's done.
bool isIdle = true;
void Update() {
if(isIdle) {
// Your movement code that gives pos
StartCoroutine(Move(pos));
}
}
IEnumerator Move(Vector2 destination) {
isIdle = false;
do {
transform.position = Vector2.MoveTowards(transform.position, destination, speed * Time.deltaTime);
yield return new WaitForEndOfFrame();
} while (transform.position != destination);
isIdle = true;
}
Let me know if you don't understand, need further clarification or if this approach doesn't work!
Related
I've been having trouble with Quaternion lerps. I'm simply looking to rotate my character 90 degrees based on their current rotation. The script below executes that almost perfectly, except for the fact that my character rotates a full 90 degrees long before rotationTime reaches the max value of 1. For some reason, the value of rotationTime is not properly synced with the progress of the lerp, and I can't seem to figure out why. What am I missing?
public class Movement : MonoBehaviour
{
bool Rotating = false;
Quaternion targetRotation;
public float rotationTime = 0f;
public float speed = 0.1F;
private Rigidbody rb;
private void Awake(){
rb = GetComponent<Rigidbody>();
}
public void Turn(InputAction.CallbackContext context){ //executes when 'E' is pressed
if (context.started && Rotating == false) {
targetRotation = Quaternion.Euler(0,transform.eulerAngles.y + 90f,0);
rotationTime = 0;
Rotating = true;
}
}
void Update() {
if (Rotating == true) {
rotationTime = rotationTime + Time.deltaTime * speed;
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation,rotationTime);
};
if (rotationTime > 1) {
Rotating = false;
}
}
}
I suspect that the main issue here is that you are using transform.rotation in your Quaternion.Lerp. You change it every frame, so every frame the start rotation will be closer to the target rotation. You should add some kind of _initRotation variable, and set it to transform.rotation in your Turn method. I mean something like this:
public void Turn(InputAction.CallbackContext context)
{
if (context.started && Rotating == false)
{
targetRotation = Quaternion.Euler(0,transform.eulerAngles.y + 90f,0);
_initRotation = transform.rotation;
rotationTime = 0;
Rotating = true;
}
}
...
void Update()
{
...
transform.rotation = Quaternion.Lerp(_initRotation, targetRotation,rotationTime);
...
}
Also, you have a logical issue with the lerp function. It does not affect the result in your particular case, but it can cause problems later.
You increment your rotation time by Time.deltaTime * speed every frame, it is not correct as it is not time passed from the start of the rotation.
According to the Quaternion.Lerp documentation, t value is always clamped to [0, 1]. So it is more convenient to use normalized time value instead of abstract speed value (right now it has no physical sense, it is just a multiplier).
It would be much clearer to use something like this:
void Update()
{
...
rotationTime += Time.deltaTime;
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationTime / fullRotationTime);
...
}
Generally, I almost always work with carriers, and I recommend that you do the same.
public class Movement : MonoBehaviour
{
bool Rotating = false;
Vector3 targetRotation;
public float rotationTime = 0f;
public float speed = 0.1F;
private Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void Turn(InputAction.CallbackContext context)
{ //executes when 'E' is pressed
if (context.started && Rotating == false)
{
targetRotation = new Vector3(0, transform.eulerAngles.y + 90f, 0);
rotationTime = 0;
Rotating = true;
}
}
void Update()
{
if (Rotating == true)
{
rotationTime = rotationTime + Time.deltaTime * speed;
transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, targetRotation, rotationTime);
};
if (rotationTime > 1)
{
Rotating = false;
}
}
}
Also consider using coroutines for more readable code and to improve performance.
Good work!
As it was mentioned already by this answer one of your main issues is that every time you use a new transform.rotation as interpolation start point
=> Your rotation starts fast and then gets slower and slower the closer you reach the target value.
There other issues here though:
You are using the transform.rotation.eulerAngles! From the API:
When using the .eulerAngles property to set a rotation, it is important to understand that although you are providing X, Y, and Z rotation values to describe your rotation, those values are not stored in the rotation. Instead, the X, Y & Z values are converted to the Quaternion's internal format.
When you read the .eulerAngles property, Unity converts the Quaternion's internal representation of the rotation to Euler angles. Because, there is more than one way to represent any given rotation using Euler angles, the values you read back out may be quite different from the values you assigned. This can cause confusion if you are trying to gradually increment the values to produce animation.
To avoid these kinds of problems, the recommended way to work with rotations is to avoid relying on consistent results when reading .eulerAngles particularly when attempting to gradually increment a rotation to produce animation. For better ways to achieve this, see the Quaternion * operator.
And then in general, since I see there is a Rigibody involved you shouldn't set or read anything directly via the Transform component at all but rather only go through that rigidbody! Otherwise you might break/fight against the physics resulting in strange behavior and breaking collision detection.
In your case in my eyes it is way easier to control the entire thing in a Corouine which avoids the need for all the class fields and imho is way easier to understand, control and maintain:
public class Movement : MonoBehaviour
{
public float speed = 0.1F;
[SerializeField] private Rigidbody rb;
private bool isRotating = false;
private void Awake()
{
if(!rb) rb = GetComponent<Rigidbody>();
}
public void Turn(InputAction.CallbackContext context)
{
//executes when 'E' is pressed
if (context.started && !isRotating)
{
StartCoroutine(RotateRoutine());
}
}
private IEnumerator RotateRoutine()
{
// little safety check first
if(Mathf.Approximately(speed, 0f)
{
yield break;
}
// Just to be really sure you avoid any concurrent routines
if (isRotating)
{
yield break;
}
// Lock so no other routine ca be started
isRotating = true;
// wait until we are in the next physics frame
yield return new WaitForFixedUpdate();
// store the initial rotation -> go throug the rigibody not the transform
var start = rb.rotation;
var end = start * Quaternion.Euler(0, 90f, 0);
var duration = 1 / speed;
for (var rotationTime = 0f; rotationTime < duration; rotationTime += Time.deltaTime)
{
// this would be a linear growing factor from 0 to 1
var factor = rotationTime / duration;
// optionally you could add ease in and out at the ends
// basically you can add whatever curve function you like to grow from 0 to 1 within the given rotationTime
factor = Mathf.SmoothStep(0, 1, rotationTime);
// interpolate from start to end while the factor grows from 0 to 1
var rotation = Quaternion.Slerp(start,end, factor);
// again for rigibdoy rather do this instead of going through transform
rb.MoveRotation();
// again wait for the next physics update
yield return new WaitForFixedUpdate();
}
// Just to be sure to end on clean values
rb.MoveRotation(end);
// release the lock for the next routine to start
isRotating = false;
}
}
Hey Guys I've been having a problem lately that I cant seem to solve.
A sprite is supposed to roam around (as it does) while nothing is inside its radius, however if the player moves close to it the sprite should theoretically move towards it and stop roaming.
The sprite doesn't follow the player and cant even see its tag since I cant even see the contents of the "Collider2D[] hits".
using System.Collections.Generic;
using UnityEngine;
public class FireCultist : MonoBehaviour
{
public float moveTimeSeconds; //Time it will take object to move, in seconds.
private float xMax = 10.0f; // The boundaries of the spawn area
private float yMax = 10.0f;
private float xMin = -10.0f; // The boundaries of the spawn area
private float yMin = -10.0f;
public int xDistanceRange; // The max distance you can move at one time
public int yDistanceRange;
private BoxCollider2D boxCollider; //The BoxCollider2D component attached to this object.
private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object.
private float inverseMoveTime; //Used to make movement more efficient.
public Vector2 start;
public Vector2 end;
public bool roam = true;
public Collider2D[] hits;
void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
rb2D = GetComponent<Rigidbody2D>();
inverseMoveTime = 1f / moveTimeSeconds;
InvokeRepeating("RandomMove", 0.0f, 5.0f);
}
void Update()
{
Collider2D[] hits = Physics2D.OverlapCircleAll(transform.position, 10); // returns all colliders within radius of enemy
int i = 0;
while(hits.Length > i)
{
Debug.Log("Sees");
Debug.Log(hits[i]);
i++;
}
followPlayer();
if (roam)
{
Debug.Log("Roam");
transform.position = Vector2.MoveTowards(transform.position, end, inverseMoveTime * Time.deltaTime); //Random move to new position
}
}
public void followPlayer()
{
foreach (Collider2D hit in hits)
{
if (hit.tag == "Player") // if the player is within a radius
{
Debug.Log("Chasing Player");
transform.position = Vector2.MoveTowards(transform.position, GameObject.Find("Prefabs/Player").GetComponent<Transform>().position, inverseMoveTime * Time.deltaTime); // chase player
roam = false;
}
else
{
Debug.Log("Continues");
roam = true; // Continue RandomMove()
}
}
}
public void RandomMove() // gets random coordinates near enemy and moves there
{
float xDistance = Random.Range(-xDistanceRange, xDistanceRange); // check
float yDistance = Random.Range(-yDistanceRange, yDistanceRange);// check
if (xDistance < xMax && xDistance > xMin && yDistance < yMax && yDistance > yMin && roam == true) // If within boundaries of walking space
{
start = transform.position;
end = start + new Vector2(xDistance, yDistance);
Debug.Log("Roaming From : " + start + " To : " + end);
}
}
}
The roaming algorithm works however not too sure about the tag detection.
The script belongs to this enemy object
Player Object Properties
It looks like you are declaring a new hits variable during every update instead of using your class-level variable. This means the variable inside of followPlayer() will never be instantiated, and the information will not be passed between the two methods.
Try this:
void Update()
{
hits = Physics2D.OverlapCircleAll(transform.position, 10);
//...
}
You might also consider attaching a trigger collider to the enemy which sends a notification when the player enters/exits the trigger instead of relying on OverlapCircleAll()
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Player"){
roam = false;
}
}
void OnTriggerExit2D(Collider2D col)
{
if(col.gameObject.tag == "Player"){
roam = true;
}
}
I'm trying to make a patrolling AI character that will move from point to point.
The patrol part works perfectly. However, the problem is that the sprite only faces right. When it turned the sprite stays facing the same direction.
I have tried to change the transform rotation using transform.rotate, transform.rotation, transform.Quaternion and making a variable to store the rotation value yet they all kick errors back. The errors are usually made from the rotate/rotation functions not being compatible with any of the attempts I have tried.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// To do:
/// - make rotation of enemy sprite work when reaching the end of patrol area
/// - create attack function
/// </summary>
public class Enemy : MonoBehaviour
{
public int health;
public float speed;
public GameObject bloodEffect;
public Transform[] moveSpots; //patrol spots
public float startWaitTime; //start countdown till move to next spot
private Rigidbody2D rb;
private Animator anim;
private int randomSpot; //number of patrol spots
private float waitTime; //how long enemy stays at patrol spot for
// Start is called before the first frame update
void Start()
{
waitTime = startWaitTime; //make waittime equal to startwaittime
anim = GetComponent<Animator>();
randomSpot = Random.Range(0, moveSpots.Length); //choose a random first spot
}
// Update is called once per frame
void Update()
{
Vector3 spriteRotation = new Vector3(0, randomSpot, 0);
transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime); //move toward first patrol area
transform.eulerAngles = spriteRotation;
if (Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.5f) //asks if patrol point is further that .5f away from enemy
{
if (waitTime <= 0) //if waitTime less than or equal to 0
{
randomSpot = Random.Range(0, moveSpots.Length); //picks new patrol point
waitTime = startWaitTime; //restarts countdown clock
}
else
{
waitTime -= Time.deltaTime; //counts down clock till next point
}
}
if (health <= 0)
{
Destroy(gameObject);
}
}
public void TakeDamage(int damage)
{
Instantiate(bloodEffect, transform.position, Quaternion.identity);
Debug.Log("Blood effect played");
health -= damage;
Debug.Log("Damage Taken");
}
}
The expected results for this code is that a random point will be chosen and the AI will move toward that chosen point. Once there it will stay idle for a specified amount of time before turning and moving to a new spot.
The actual result is mostly the same as expected only the sprite does not turn around but instead continues to face to the right even when the AI is moving left.
Image of area
the enemy is the dark red cube, the movepoints are the points that the enemy patrols between. when it reaches the left point, he should turn to the right and go back but this is not what happens, instead he just moves back and forth with no rotation. ive tried the SpriteRenderer.flipX route and it only works one time and then sticks with that direction.
The SpriteRenderer Component has a Flip attribute you could use for this.
You can access it in code
SpriteRenderer.flipX = true;
It will only flip the sprite and won't change anything else, so double check if your colliders are still in the right space :) See more in the documentation
Good luck
randomSpot is an index not an angle. So using
transform.eulerAngles = new Vector3(0, randomSpot, 0);
doens't make any sense to me ...
Instead of rotating you could also flip the sprite/Image by using a negative scale like e.g.
// Update is called once per frame
private void Update()
{
// however you determin if facing left or right
// you e.g. simply check whether the target position
// is left or right of you
var difference = moveSpots[randomSpot].position - transform.position;
var isFacingRight = difference.x > 0;
if (isFacingRight && transform.localScale.x < 0
|| !isFacingRight && transform.localScale.x > 0)
{
FlipSprite();
}
}
private void FlipSprite()
{
// invert the local X-axis scale
transform.localScale = new Vector3(-spriteTransform.localScale.x, spriteTransform.localScale.y, spriteTransform.localScale.z);
}
Script used for the example
private void Update()
{
// works only in a ScreenOverlay Canvas
var targetPosition = Input.mousePosition;
var difference = targetPosition - transform.position;
var isFacingRight = difference.x > 0 ? true : false;
if (isFacingRight && transform.localScale.x < 0
|| !isFacingRight && transform.localScale.x > 0)
{
FlipSprite();
}
// simply only move left or right on the x-axis towards the mouse
transform.position = Vector3.MoveTowards(transform.position, new Vector3(targetPosition.x, 218, 0), Time.deltaTime * 100);
}
private void FlipSprite()
{
// invert the local X-axis scale
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
You can try:
if (moveSpot[randomSpot].transform.position.x > transform.position.x) {
transform.localScale = new Vector3(-1, 1, 1);
}
else {
transform.localScale = new Vector3(1, 1, 1);
}
I've been trying to build a raycast controller for a 2D game, and have followed some tutorial series to help me better understand how this is done. So far everything has been going well, and I've actually followed several tutorials on this topic to completion without issue.
However, while using this current character controller I am getting a slew of errors on play, even with no compiler errors present. I have never seen this error, and have not been able to find a solution online about how to fix it. Basically my character disappears on play (I assume its being moved infinitely to the left).
I get two errors: "transform.position assign attempt is not valid. Input position is { -infinity, 0,0 }," and "Invalid world AABB. Object is too large or too far away from origin."
The error occurs on lines 90:
public void LateUpdate()
{
Move(Velocity * Time.deltaTime);
}
and 126:
characterTransform.Translate(deltaMovement, Space.World);
I have tried a bunch of different things, including changing my character's scale, changing Vector2s to Vector3s, removing Space.World, and calling transform.Translate directly (as opposed to using my characterTransform). Nothing seems to work, and for some reason my camera gives me an error sometimes too, though it is hard to reproduce. If I remove either line of code I get no errors, but obviously my character cannot move.
Screenshot of the errors: https://imgur.com/a/24KIN
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Handles the character movement with raycasts
/// </summary>
public class CharacterController2D : MonoBehaviour {
//Defines the number of rays
private const int totalHorizontalRays = 8;
private const int totalVeritcalRays = 4;
private RaycastOrigins raycastOrigins; //References the RayCastOrigins struct
private const float skinWidth = .02f; //Defines the skin width of the rays, which places the origin point of the rays slightly inside the character's box collider
private static readonly float slopeLimitTanget = Mathf.Tan(75f * Mathf.Deg2Rad);
public LayerMask platformMask; //Defines the layermask that will be used to determine how different layers interact with the character
public ControllerParameters2D defaultParameters; //References the ControllerParameters2D class
public ControllerState2D State { get; private set; } //References the ControllerState2D class
public ControllerParameters2D Parameters { get { return overrideParameters ?? defaultParameters; } } //Returns updated parameters, or default parameters if overrideParameters is null
public Vector2 Velocity { get { return velocity; } } //Defines the character's velocity
public bool CanJump { get { return false; } } //Defines whether or not the character can jump
public bool HandleCollisions { get; set; } //Defines whether or not the character needs to handle collisions (because it is colliding with something)
private Vector2 velocity; //The field for the Velocity property
private BoxCollider2D boxCollider; //References the box collider on the character
private ControllerParameters2D overrideParameters; //References the updated parameters (that is, the updated parameters, not the default ones)
private Transform characterTransform; //References the character's transform
private Vector3 localScale; //References the character's scale
//The distance between raycasts
private float horizontalDistanceBetweenRays;
private float verticalDistanceBetweenRays;
private struct RaycastOrigins //Stores the value types that define where the raycasts are created on the box collider
{
public Vector2 topLeft, topRight; //Creates variables to define the upper position of the raycasts
public Vector2 bottomLeft, bottomRight; //Creates variables to define the lower position of the raycasts
}
public void Awake()
{
State = new ControllerState2D(); //Accesses the ControllerState2D script
boxCollider = GetComponent<BoxCollider2D>(); //Accesses the character's box collider
characterTransform = transform; //Accesses the character's transform
localScale = transform.localScale; //Accesses the character's scale
//Gets the ray spacing
horizontalDistanceBetweenRays = CalculateHorizontalRaySpacing();
verticalDistanceBetweenRays = CalculateVerticalRaySpacing();
}
public void Start()
{
}
public void AddForce(Vector2 force)
{
velocity += force;
}
public void SetForce(Vector2 force)
{
velocity = force;
}
public void SetHorizontalForce(float x)
{
velocity.x = x;
}
public void SetVerticalForce(float y)
{
velocity.y = y;
}
public void Jump()
{
}
public void LateUpdate()
{
Move(Velocity * Time.deltaTime); //Moves the character per its velocity, scaled by time
}
public void OnTriggerEnter2D(Collider2D other)
{
}
public void OnTriggerExit2D(Collider2D other)
{
}
private void Move(Vector2 deltaMovement)
{
var wasGrounded = State.IsCollidingBelow; //Keeps track of whether or not the character is grounded
State.Reset(); //Resets the state
if (HandleCollisions) //If the character should handle collisions
{
HandlePlatforms();
CalculateRaycastOrigins();
if (deltaMovement.y < 0 && wasGrounded) //If the character is moving down, and was previously grounded...
{
ClimbDownSlope(ref deltaMovement);
}
if (Mathf.Abs(deltaMovement.x) > .001f) //If the character is moving left or right...
{
MoveHorizontally(ref deltaMovement);
}
MoveVertically(ref deltaMovement); //Calls the MoveVertically method always, since the character always has the force of gravity enacted on it
}
characterTransform.Translate(deltaMovement, Space.World); //Moves the character after all potential movement scenarios have been accounted for
if (Time.deltaTime > 0)
{
velocity = deltaMovement / Time.deltaTime; //Sets the current velocity equal to the change in movement
}
//Clamps the velocity to the maximum x and y velocity defined in Parameters
velocity.x = Mathf.Min(velocity.x, Parameters.maxVelocity.x);
velocity.y = Mathf.Min(velocity.y, Parameters.maxVelocity.y);
if (State.IsMovingUpSlope) //If the character is moving up a slope...
{
velocity.y = 0;
}
}
private void MoveHorizontally(ref Vector2 deltaMovement)
{
var isGoingRight = deltaMovement.x > 0; //Defines if the character is going right
var rayDistance = Mathf.Abs(deltaMovement.x) + skinWidth; //Defines the distance of the raycasts
var rayDirection = isGoingRight ? Vector2.right : -Vector2.right; //Defines in which direction the rays will shoot, depdending on character direction
var rayOrigin = isGoingRight ? raycastOrigins.bottomRight : raycastOrigins.bottomLeft; //Defines the current ray origin
for (var i = 0; i < totalHorizontalRays; i++) //Loops through each of the 8 horizontal rays
{
var rayVector = new Vector2(rayOrigin.x, rayOrigin.y + (i * verticalDistanceBetweenRays)); //Builds the rays (stacking them up with each ray that is added)
Debug.DrawRay(rayVector, rayDirection * rayDistance, Color.red);
var rayCastHit = Physics2D.Raycast(rayVector, rayDirection, rayDistance, platformMask); //Actually draws the rays
if (!rayCastHit) //If the raycast hits something... (rayCastHit is true)
{
continue;
}
if (i == 0 && ClimbUpSlope(ref deltaMovement, Vector2.Angle(rayCastHit.normal, Vector2.up), isGoingRight)) //If the character is now climbing a slope...
{
break;
}
deltaMovement.x = rayCastHit.point.x - rayVector.x; //Clamps horizontal movement based on ray collision
rayDistance = Mathf.Abs(deltaMovement.x); //Clamps the ray distance based on how far the character is allowed to move (i.e. ensures the rays end at walls)
if (isGoingRight) //If the character is going right...
{
deltaMovement.x -= skinWidth; //Ensures that the character moves with the correct value (otherwise would be able to move slightly more based on skinWidth value)
State.IsCollidingRight = true;
}
else //If the character is going left...
{
deltaMovement.x += skinWidth;
State.IsCollidingLeft = true;
}
if (rayDistance < skinWidth + .0001f) //If a collision gets bugged for some reason...
{
break;
}
}
}
private void MoveVertically(ref Vector2 deltaMovement)
{
}
private void ClimbDownSlope(ref Vector2 deltaMovement)
{
}
private bool ClimbUpSlope(ref Vector2 deltaMovement, float angle, bool isGoingRight)
{
return false;
}
private void HandlePlatforms()
{
}
private float CalculateHorizontalRaySpacing()
{
Bounds bounds = boxCollider.bounds; //Sets the 'bounds' variable equal to the bounds of the box collider on the game object
bounds.Expand(skinWidth * -2); //Enforces the skinWidth variable
return bounds.size.y / (totalHorizontalRays - 1); //Ensures that all rays are spaced evenly on the sides of the box collider
}
private float CalculateVerticalRaySpacing()
{
Bounds bounds = boxCollider.bounds; //Sets the 'bounds' variable equal to the bounds of the box collider on the game object
bounds.Expand(skinWidth * -2); //Enforces the skinWidth variable
return bounds.size.x / (totalVeritcalRays - 1); //Ensures that all rays are spaced evenly on the bottom and top of the box collider
}
private void CalculateRaycastOrigins()
{
Bounds bounds = boxCollider.bounds; //Sets the 'bounds' variable equal to the bounds of the box collider on the game object
bounds.Expand(skinWidth * -2); //Enforces the skinWidth variable
//Creates the starting positions of the raycasts
raycastOrigins.bottomLeft = new Vector2(bounds.min.x, bounds.min.y);
raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y);
raycastOrigins.topLeft = new Vector2(bounds.min.x, bounds.max.y);
raycastOrigins.topRight = new Vector2(bounds.max.x, bounds.max.y);
}
}
After doing some research, it seems this is a bug that can sometimes occur.
Not sure why I didn't try this sooner, but reinstalling Unity fixed all the issues...
This question already has answers here:
Rotate GameObject over time
(2 answers)
Closed 5 years ago.
in my project i have a bridge at the moment when i colide with the bridge it rotates and don't stop rotate, what i want is to rotate that bridge trough a specific point and stop rotate, that bridge is inside a gameobject that is my pivotPoint in general i rotate the pivotPoint not the bridge, so i did this:
using UnityEngine;
using System.Collections;
public class fallBridge : MonoBehaviour {
private Rigidbody ball;
public GameObject bridgePivot;
private bool colided;
private bool rotating = true;
// Update is called once per frame
void Start(){
colided = false;
}
void Update () {
if (colided) {
if (rotating) {
Vector3 to = new Vector3 (0, 0, -85);
if (Vector3.Distance (bridgePivot.transform.eulerAngles, to) > 0.01f) {
bridgePivot.transform.eulerAngles = Vector3.Lerp (bridgePivot.transform.rotation.eulerAngles, to, Time.deltaTime);
} else {
bridgePivot.transform.eulerAngles = to;
rotating = false;
}
}
}
}
void OnCollisionEnter(Collision other)
{
ball = GameObject.FindWithTag ("Player").GetComponent<Rigidbody> ();
if (other.gameObject.tag == "Player" && ball.transform.localScale == new Vector3(2.0f,2.0f,2.0f)) {
Debug.Log("ENTER");
colided = true;
}
}
}
what am i doing wrong?? the colision detection works perfectly but on the update method it never stops rotate :S
You should do this with coroutine. Call the coroutine function and pass in the GameOjbect to rotate and the angle to rotate to when OnCollisionEnter is called. You can read how this function work here.
Te example below will rotate the GameObject -85 degree in z-axis within 3 seconds.
You can change that to whatever suits you.
public class fallBridge : MonoBehaviour
{
private Rigidbody ball;
public GameObject bridgePivot;
bool rotating = false;
void OnCollisionEnter(Collision other)
{
ball = GameObject.FindWithTag("Player").GetComponent<Rigidbody>();
if (other.gameObject.CompareTag("Player") && ball.transform.localScale == new Vector3(2.0f, 2.0f, 2.0f))
{
Debug.Log("ENTER");
Vector3 rotationAngle = new Vector3(0, 0, -85);
StartCoroutine(RotateObject(bridgePivot, rotationAngle, 3f));
}
}
IEnumerator RotateObject(GameObject gameObjectToMove, Vector3 eulerAngles, float duration)
{
if (rotating)
{
yield break;
}
rotating = true;
Vector3 newRot = gameObjectToMove.transform.eulerAngles + eulerAngles;
Vector3 currentRot = gameObjectToMove.transform.eulerAngles;
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
gameObjectToMove.transform.eulerAngles = Vector3.Lerp(currentRot, newRot, counter / duration);
yield return null;
}
rotating = false;
}
The error is in this line:
bridgePivot.transform.eulerAngles = Vector3.Lerp (bridgePivot.transform.rotation.eulerAngles, to, Time.deltaTime);
When you use Lerp you typically have a fixed beginning and end, and you make the last parameter (t) go from 0 to 1. In your case the endpoint is fixed, the t parameters is fixed also and you vary your start. This means that each update you take a small step towards your goal, but this step is a percentage of the way. So each update you come closer, and your next step will be smaller.
What you should do is remember where you were when you started, and at what time you started. You also need to define a speed for your bridge. Then you can move the bridge from start to end and you get control over the speed.
public class fallBridge : MonoBehaviour {
private Rigidbody ball;
public GameObject bridgePivot;
public float rotateDuration = 2; // Time in seconds
// When you begin rotating you fill these three variables
private float startTime;
private Vector3 from;
private bool rotating = false;
// If the target doesn't change you might as well define it beforehand
private Vector3 to = new Vector3 (0, 0, -85);
void Update () {
if (rotating) {
float t = (Time.time - startTime) / rotateDuration;
if (t < 1) {
bridgePivot.transform.eulerAngles = Vector3.Lerp (from, to, t);
} else {
bridgePivot.transform.eulerAngles = to;
rotating = false;
}
}
}
void OnCollisionEnter(Collision other)
{
ball = GameObject.FindWithTag ("Player").GetComponent<Rigidbody> ();
if (other.gameObject.tag == "Player" && ball.transform.localScale == new Vector3(2.0f,2.0f,2.0f)) {
Debug.Log("ENTER");
startTime = Time.time; // Begin now
from = bridgePivot.transform.eulerAngles; // Remember the start position
rotating = true; // Signal to start rotating
}
}
}