I mean that when the character is walking or running and getting to the clicked point he change the state in the animator from walk/run to idle so it looks like he walk then stop there is no animation between the walk/run and the start/stop.
I have 3 states in the animator. HumanoidWalk, HumanoidRun, HumanoidIdle.
I need something like fading.
For example if in the line:
_animator.CrossFade("Walk", 0);
I will change the 0 to 1 so when he start "Walk" it will be a bit slowly to walking speed. But in "Idle" if i will change it to 1 it will be something else not fading until he stop.
In other words i want to add fading effects when character start/stop walking/running and also when i click/double click and he switch between Walk and Run. Make some fade effects so it will not switch between the states so fast.
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour
{
public int speed = 5; // Determines how quickly object moves towards position
public float rotationSpeed = 5f;
private Vector3 targetPosition;
private Animator _animator;
private Vector3 destination;
private Quaternion targetRotation;
public float clickDelta = 0.35f; // Max between two click to be considered a double click
private bool click = false;
private float clickTime;
void Start()
{
_animator = GetComponent<Animator>();
_animator.CrossFade("Idle", 0);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (click && Time.time <= (clickTime + clickDelta))
{
_animator.CrossFade("Run", 0);
click = false;
}
else
{
click = true;
clickTime = Time.time;
}
_animator.CrossFade("Walk", 0);
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast(ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
targetPosition = ray.GetPoint(hitdist);
targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
destination = targetPosition;
}
}
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed);
if ((transform.position - destination).magnitude < 0.7f)
{
_animator.CrossFade("Idle", 0);
}
}
}
If you increase your transform duration value a little (like 0.25), then you can get a smooth transition between states. Also uncheck "fixed duration".
Related
Im making a game where you click and drag with the mouse then release to launch the player. But sometimes the player gets launched in the opposite direction of where it should go. I made a debug output to show you the different values. Here is the output
In that image for example you can see that the Vector2 of force * power is positive on the y axis, but the player launched downwards, and the same happens Viceversa. I think its also worth to note that this happens inconsistantly for some reason. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public GameObject player;
public float power = 10f;
public Rigidbody2D rb;
public float maxSpeed;
public Vector2 minPower;
public Vector2 maxPower;
TragectoryLine tl;
Camera cam;
public Vector2 force;
public Vector3 startPoint;
public Vector3 endPoint;
public Vector3 currentPoint;
public Vector3 startPointMouse;
public bool isPulling = false;
float distance;
private void Start()
{
cam = Camera.main;
tl = GetComponent<TragectoryLine>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
startPointMouse = cam.ScreenToWorldPoint(Input.mousePosition);
startPointMouse.z = 15;
}
if (Input.GetMouseButton(0))
{
startPoint = player.transform.position;
startPoint.z = 15;
isPulling = true;
Vector3 currentPoint = cam.ScreenToWorldPoint(Input.mousePosition);
currentPoint.z = 15;
tl.RenderLine(startPoint, currentPoint);
}
if (Input.GetMouseButtonUp(0))
{
endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
endPoint.z = 15;
isPulling = false;
tl.EndLine();
distance = startPointMouse.magnitude - endPoint.magnitude;
if (distance < 0)
{
distance = -distance;
}
if (distance >= 1)
{
rb.AddForce(force * power, ForceMode2D.Impulse);
}
force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));
Debug.Log("distance" + distance);
Debug.Log("start" + startPoint);
Debug.Log("end" + endPoint);
Debug.Log("force" +force);
Debug.Log("force * power" + force * power);
}
}
private void FixedUpdate()
{
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
}
}
Here I added the force using rb.AddForce(force * power, ForceMode2D.Impulse); when the force * power value was positive on the y axis. So why did it go to the opposite direction???
This was working perfectly fine before i tried implementing a feature where the player has to move the mouse a certain distance or else it wont launch. I have tried removing it but it doesnt seem to make a difference. I think I changed something in the code that ruined it but I cant figure out what! Please help!
I'm trying to write a script for my enemy movements. Here is my code:
public class EnemiesMovement : MonoBehaviour
{
private bool isFacingRight = false;
public float speed = 10f;
private float startPoint;
private float endPoint;
public float unitMovement = 2f;
private Rigidbody2D enemy;
private Animator anim;
bool moveRight;
// Start is called before the first frame update
void Start()
{
enemy = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
startPoint = enemy.position.x;
endPoint = startPoint + unitMovement;
}
// Update is called once per frame
void Update()
{
if (enemy.position.x >= endPoint)
moveRight = false;
if (enemy.position.x <= startPoint)
moveRight = true;
if (moveRight)
{
enemy.velocity = new Vector2(-transform.localScale.x, 0) * speed;
if (!isFacingRight)
Flip();
}
if (!moveRight)
{
enemy.velocity = new Vector2(transform.localScale.x, 0) * speed;
if (isFacingRight)
Flip();
}
}
void Flip()
{
isFacingRight = !isFacingRight;
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
}
}
The movement of the enemy is right, but after the enemy flips its sprites, it doesn't change the direction of its movement. Basically, it continues to the right, even though its sprite has turned left. Can someone show me how I can fix this?
My enemy spite has a positive scale facing to the left.
Velocity is affected by the scale property.
So if you change the scale negative, everything on this GameObject flips, it's not necessary to change the velocity direction.
Are you getting bewildered? You can try another method to flip the sprite.
GetComponent<SpriteRenderer>().flipX = true;
This only flips the sprite renderer, other things are working as normal in its world space.
Another suggests as Unity documented it's better to change Rigidbody's property in the FixedUpdate.
I was actually able to do this with an enemy but for some reason I can't get it to work if it's the player.
See, the player is in a default, idle animation. When I press the arrow key from the opposite direction its facing at (default is the right when game starts -->), I want it to play a turning animation before the sprite flips over its x scale.
However what it's doing right now when I press the arrow key to turn him, is that firstly, it quickly flips the sprite over, then performs the animation as if it hadn't been flipped yet, then flips over to the other direction again.
In my animator, the idle has no exit time to the flip node and the flip node does have an exit time back to idle, just in case you would inquire. I've tried invoking a timer here and there as well but so far no luck. Can anyone help please?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class tulMoveMount : MonoBehaviour {
private Animator anim;
private Rigidbody2D rb;
public Image manaBar;
public LayerMask whatIsGround;
private bool grounded = false;
public Transform groundCheck;
public float groundCheckRadius;
private bool goRight = true;
private bool jump;
private bool turn = false;
private bool idle = true;
private bool mountOff;
private bool turnComplete = false;
public float runSpeed;
public float walkSpeed;
private float move;
public float turnDelay = 2.25f;
public float timer3 = 2.26f;
void Start ()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
grounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
timer -= Time.deltaTime;
turnDelay -= Time.deltaTime;
HandleMovement ();
}
void HandleMovement()
{
float move = Input.GetAxis ("Horizontal");
float moveV = Input.GetAxis ("Vertical");
{
rb.velocity = new Vector2 (move * walkSpeed, rb.velocity.y);
anim.SetFloat ("walkSpeed", Mathf.Abs (move));
}
if (!goRight && move > 0) {
FlipConditions ();
Invoke ("ResetValues",timer3 );
Flip ();
turnComplete = false;
}
if (goRight && move < 0) {
FlipConditions ();
Invoke ("ResetValues",timer3 );
Flip ();
}
}
void FlipConditions()//
{
idle = false;
turn = true;
anim.SetTrigger ("turn");
idle = true;
anim.SetTrigger ("idle");
}
void Flip()
{
goRight = !goRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
turnComplete = false;
}
void ResetValues()
{
idle = true;
anim.SetTrigger ("idle");
}
}
You can try to flip the sprite in LateUpdate() after you perform perform any animation in Update(). Try something like that, placing the animation in Update:
// store references to components on the gameObject
Transform _transform;
Rigidbody2D _rigidbody;
// hold player motion in this timestep
float vx;
float vy;
float MoveSpeed;
void Awake () {
// get a reference to the components we are going to be changing and store a reference for efficiency purposes
transform = GetComponent<Transform> ();
rigidbody = GetComponent<Rigidbody2D> ();
}
// this is where most of the player controller magic happens each game event loop
void Update()
{
// determine horizontal velocity change based on the horizontal input
vx = Input.GetAxisRaw ("Horizontal");
// get the current vertical velocity from the rigidbody component
vy = rigidbody.velocity.y;
// Change the actual velocity on the rigidbody
rigidbody.velocity = new Vector2(vx * MoveSpeed, vy);
}
// Checking to see if the sprite should be flipped
// this is done in LateUpdate since the Animator may override the localScale
// this code will flip the player even if the animator is controlling scale
void LateUpdate()
{
// get the current scale
Vector3 localScale = transform.localScale;
if (vx > 0) // moving right so face right
{
facingRight = true;
} else if (vx < 0) { // moving left so face left
facingRight = false;
}
// check to see if scale x is right for the player
// if not, multiple by -1 which is an easy way to flip a sprite
if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
localScale.x *= -1;
}
// update the scale
transform.localScale = localScale;
}
Below is a copy of my player movement script which contains functions to animate my character moving left and right, jumping and shooting his bow. I have also been able to get my character to transition from shooting his bow to being in an alert animation, but I am wondering how to write the code so that for 5 seconds after I shoot my bow I will be alert before going back to my default "idle" animation.
I would also like my character to be able to walk around (i.e. transition the alert animation to the walk animation) while being alert, but if he stops moving he goes back to alert. Currently my character will go back to idle if he walks during his alert stance. The script below, specifically lines 98-102 (my "playerAlert" function) present another problem in that my character cannot perform his "shoot" animation after this function has occurred, but I do not know/can't wrap my head around how to code what I mentioned above.
I am using Unity 5.6.
I appreciate any help you guys may be able to give me.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player_1_controller : MonoBehaviour {
Rigidbody2D myRB;
Animator myAnim;
bool facingRight;
//movement variables
public float maxSpeed;
//jumping variables
bool grounded = false;
float groundCheckRadius = 0.2f;
public LayerMask groundLayer;
public Transform groundCheck;
public float jumpHeight;
//arrow shooting variables
bool firing = true;
public float arrowShoot;
public Transform arrowTip;
public GameObject arrow;
public float fireRate = 0.5f;
public float nextFire = 0f;
// Use this for initialization
void Start () {
myRB = GetComponent<Rigidbody2D> ();
myAnim = GetComponent<Animator> ();
facingRight = true;
}
// Update is called once per frame
void Update () {
//player jump
if (grounded && Input.GetButtonDown ("Jump")) {
grounded = false;
myAnim.SetBool ("isGrounded", grounded);
myRB.AddForce (new Vector2 (0, jumpHeight));
}
//player shooting
if (grounded && Input.GetButtonDown ("Fire1")) {
myAnim.SetBool ("arrowShoot", firing);
Invoke ("fireArrow", 1);
}
}
void FixedUpdate() {
//player movement
float move = Input.GetAxis ("Horizontal");
myAnim.SetFloat ("speed", Mathf.Abs (move));
myRB.velocity = new Vector2 (move * maxSpeed, myRB.velocity.y);
if (move > 0 && !facingRight) {
flip ();
} else if (move < 0 && facingRight) {
flip ();
}
//player jump; check if we are grounded - if not, then we are falling
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
myAnim.SetBool ("isGrounded", grounded);
myAnim.SetFloat ("verticalSpeed", myRB.velocity.y);
}
void flip () {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
void fireArrow() {
if (Time.time > nextFire) {
nextFire = Time.time + fireRate;
if (facingRight) {
Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
} else if (!facingRight) {
Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 180)));
}
}
playerAlert ();
}
void playerAlert () {
firing = false;
myAnim.SetBool ("arrowShoot", firing);
}
}
Invoke can help you here. excerpt:
void Start()
{
Invoke("LaunchProjectile", 2);
}
void LaunchProjectile()
{
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
You can use that to call(invoke) the "back to idle" function after 5 seconds.
Have you considered implementing it inside the animator?
You could create a transition from your Alert animation to your Idle animation, with a fixed exit time of 5 seconds.
This way, after 5 seconds of being in the Alert animation, it will transition to the Idle animation.
So here's the problem in video form
https://pbs.twimg.com/tweet_video/CPsvjgbWoAACKCp.mp4
When not moving the ship the shield moves around just fine, but when you start moving it can only drag behind you and move a little bit, which is just no good at all. I can't figure out what I've done wrong here!
public class ShieldMovement : MonoBehaviour {
public Transform target; //player shield is attaced to
public float circSpeed = 0.1f; // Speed Shield moves around ship
private Vector3 direction = Vector3.up;
private float distance = 0.8f; // distance from player so it doesn't clip
private float deadzone = 0.15f;
private float separation;
private bool canMove = true;
private Vector3 shipPos;
private Rigidbody2D tRB;
private Rigidbody2D rb;
// Use this for initialization
void Start ()
{
tRB = target.GetComponent<Rigidbody2D>();
rb = GetComponent<Rigidbody2D>();
}
void OnCollisionEnter2D (Collision2D other)
{
canMove = false;
}
void OnCollisionStay2d(Collision2D other)
{
canMove = false;
}
void OnCollisionExit2D (Collision2D other)
{
canMove = true;
}
// Update is called once per frame
void Update () {
float rh = Input.GetAxisRaw("rightH");
float rv = Input.GetAxisRaw("rightV");
shipPos = target.position;
separation = Mathf.Abs((transform.position - shipPos).magnitude);
if(Mathf.Abs(rh) > deadzone || Mathf.Abs(rv) > deadzone)
{
Vector3 targetDir = new Vector3(rh, rv, 0.0f);
direction = Vector3.Slerp(transform.position-shipPos, targetDir, circSpeed);
}
Ray ray = new Ray(shipPos, direction); // cast ray in direction of point on circle shield is to go
if(canMove)
{
transform.position = ray.GetPoint(distance); //move shield to the ray as far as the distance
}
if(separation != distance) //If the shield get torn away from the ship
{
transform.position = ray.GetPoint(distance); //move shield to the ray as far as the distance
}
float angleY = transform.position.y - shipPos.y;
float angleX = -(transform.position.x - shipPos.x);
float angle = Mathf.Atan2 (angleY, angleX) * Mathf.Rad2Deg-90; //Get angle
if(Mathf.Abs(rh) > deadzone || Mathf.Abs(rv) > deadzone)
{
transform.rotation = Quaternion.AngleAxis(angle,Vector3.forward*-1); // keep shield facing outwards in respect to player
}
}
void FixedUpdate ()
{
if(!canMove)
{
tRB.velocity = new Vector2(0.0f, 0.0f);
rb.velocity = new Vector2(0.0f, 0.0f);
}
}
Thanks a million for any help :)
You need to move the shield along with the ship. You can do this by adding the ship velocity to the shield.
Something like:
shipPos = target.position;
transform.position += shipVelocity;
separation = Mathf.Abs((transform.position - shipPos).magnitude);
Or make the shield a child object of the ship.
OK, so all I needed to do was to make the shield a child AND get rid of the conditional statement around the transform.rotation so it wouldn't inherit the parent rotation and ruin the shield. It's the little things!