Unity character controller script and animator - c#

Hello so i have this script and in the void update in doesnt matter wich is first for backwards or run up it always makes the animator play the animation backwards walk or run it plays the animation half way or full way and it plays part of the idle state without it been called that means your finger is still in the on the button so it must still play backward/forwards animation over and over .
here is the code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour {
public float moveSpeed = 10f;
public float turnSpeed = 50f;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.S)) {
anim.SetBool ("isIdle", false);
anim.SetBool ("isWalkingBack", true);
transform.Translate (-Vector3.forward * moveSpeed * Time.deltaTime);
}
else
{
anim.SetBool ("isIdle", true);
anim.SetBool ("isWalkingBack", false);
}
if (Input.GetKey (KeyCode.W)) {
anim.SetBool ("isRunning", true);
anim.SetBool ("isIdle", false);
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
else
{
anim.SetBool ("isRunning", false);
anim.SetBool ("isIdle", true);
}
}
}
`

Using boolean fields may cause some problems, for example, which you described above.
I recommend to use: anim.SetInteger("unitState", someIntValue);
Configure the connections and transitions in the animator to work with the field "unitState".
In your code it will look something like this:
void Update () {
// for example
anim.SetInteger("unitState", 0); // 0 is Idle
if (Input.GetKey (KeyCode.S)) {
anim.SetInteger("unitState", -1); // -1 is WalkBack
transform.Translate (-Vector3.forward * moveSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.W)) {
anim.SetInteger("unitState", 1); // 1 is run forward
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.Space)) {
anim.SetInteger("unitState", 2); // 2 is jump
//Jump code here. for example
}
....
}

Make sure you have unchecked exit time on every transition.

Related

how can i convert a transform into a float

I am trying to take the current position of something once when collided and im not sure how to
do that could anyone help me out please?
The problem i have is that the script is grabbing the playerLocation constantly i need it so it grabs it once it collides.
basically when my object colides with something it moves towards a diferent object but i dont want it to follow it constantly i want it to get the position of that 1 object only once it has collided.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleMover : MonoBehaviour
{
public float speed = 10.0f;
public Transform playerLocation;
public float redirectSpeed;
public bool isCurrentlyColliding;
Vector3 playerposition;
private Rigidbody2D rb;
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(-speed, 0);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void Update()
{
//if (transform.position.x < -11.6f)
//{
// Destroy(this.gameObject);
//}
if (isCurrentlyColliding)
{
transform.position = Vector2.MoveTowards(transform.position, playerposition.transform.position, redirectSpeed * Time.deltaTime);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("CopyCat"))
{
playerposition = (playerLocation.transform.position);
isCurrentlyColliding = true;
}
}
}
The reason it grabs the playerLocation constantly because you are using isCurrentlyColliding which you are never making false and also using it in Update() method which calls every frame.
You can do two things (choose whichever goes well with your code) :
by making isCurrentlyColliding false inside Update() method like this:
void Update()
{
if (isCurrentlyColliding)
{
transform.position = Vector2.MoveTowards(transform.position, playerposition.transform.position, redirectSpeed * Time.deltaTime);
isCurrentlyColliding = false;
}
}
by removing isCurrentlyColliding and setting transform.position directly inside OnTriggerEnter2D() method like this:
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("CopyCat"))
{
playerposition = (playerLocation.transform.position);
transform.position = Vector2.MoveTowards(transform.position, playerposition.transform.position, redirectSpeed * Time.deltaTime);
}
}

Animation Starts but player won't move on key press in Unity

Me and 3 friends started working on game and while codding run into error that animation on player starts but it won't move. We are working in Unity(C#)
I already checked for names in Animator and code so it's not it.
Here is a code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
public Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f , 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
if(Input.GetAxis("Horizontal") > 0){
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
}
void Jump(){
if (Input.GetButtonDown("Jump")){
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f,5f), ForceMode2D.Impulse);
}
}
}
It's 2D game if It matters
You could try to create the rigidbody2d in start(), then try
rigidbody.AddForce(Vector2(moveSpeed,0), ForceMode2D.Impulse);

My object begins to spin when collides with the wall

I have in Unity a box that is followed by a camera on a plane. I'm trying to handle the collisions between the box and different objects. When it collides with different things it spins, jumps and happen weird things. I uploaded to YouTube a video to show the problem. The video.
I created an empty that has the camera and the box. This empty has rigidbody of mass 1.
The empty has a script component:
using UnityEngine;
using System.Collections;
public class Character : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision collision)
{
Debug.Log ("Entered OnCollisionEnter function");
if (collision.gameObject.name == "Wall") {
GetComponent<Rigidbody>().velocity = Vector3.zero;
Debug.Log ("Inside if statement");
}
}
}
As you can see I tried to handle the collision writing a code that stops the cube of moving.
Additional information that could help you guys:
The box
It has a box collider. Script:
using UnityEngine;
using System.Collections;
public class MoveCharacter : MonoBehaviour {
public float deltaMovement = 10f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
Moving();
}
void Moving()
{
//Moves the character to where it needs.
if (Input.GetKey (KeyCode.A)) {
transform.Translate (new Vector3 (-deltaMovement, 0f, 0f) * Time.deltaTime);
} else if (Input.GetKey (KeyCode.D)){
transform.Translate (new Vector3 (deltaMovement, 0f, 0f) * Time.deltaTime);
}
float yRotation = Camera.main.transform.eulerAngles.y;
float movementX = Mathf.Sin ((yRotation * Mathf.PI) / 180) * deltaMovement;
float movementZ = Mathf.Cos ((yRotation * Mathf.PI) / 180) * deltaMovement;
if (Input.GetKey (KeyCode.W)) {
transform.Translate (new Vector3 (movementX, 0f, movementZ) * Time.deltaTime, Space.World);
} else if (Input.GetKey (KeyCode.S)){
transform.Translate (new Vector3 (-movementX, 0f, -movementZ) * Time.deltaTime, Space.World);
}
}
}
The wall
It is a plane with mesh collider and with or without rigidbody didn't make a difference, same problem...
Any help please?
If you are using physics you shouldn't move an object my changing it's translation, you should move it by applying forces to the object, or at least adding a velocity to it. This will allow the physics engine to correctly calculate the reactions with other rigid bodies.
If you move an object my adjusting it's translation then when a collision occurs it will be as though the object has materialised into the other object to the engine as it will be moving with no velocity etc, and you will get weird behaviour.

my collision 2d doesn't work in C# on Unity

I'm learning C# while programming my game, I'm stuck doing the movement. I want my character to move continuously by pressing 'D' or 'A' once. Then, after colliding with an invisible wall while going to the right, go backwards until it hits another invisible wall and stop.
I managed to make my GameObject move, but when it collides with the wall, nothing happens. Both objects have a rigidbody2D, the same z-coordinates, and correct tags.
public class SquadMovement : MonoBehaviour {
float speed;
bool collisionRightWall = false;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.D)) {
CancelInvoke ();
InvokeRepeating ("RightMovement", Time.deltaTime, Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.A)) {
CancelInvoke ();
InvokeRepeating ("LeftMovement", Time.deltaTime, Time.deltaTime);
}
}
void RightMovement () {
speed = 10f;
transform.Translate (speed * Time.deltaTime, 0, 0);
}
void LeftMovement () {
speed = -7f;
transform.Translate (speed * Time.deltaTime, 0, 0);
}
void OnCollisionWallR (Collider2D colR) {
if (colR.gameObject.tag == "invisibleWallRight") {
collisionRightWall = true;
Debug.Log (collisionRightWall);
}
}
}
I'm using invisible walls because I don't know how to use x-coordinates, There HAS to be a more efficient way but I want to know first why this don't work. I would be glad if someone could teach me that too.
using UnityEngine;
using System.Collections;
public class SquadMovement : MonoBehaviour {
float constantspeed = 3;
float speed;
//Key inputs
void Update () {
transform.Translate (constantspeed * Time.deltaTime, 0, 0);
if (Input.GetKeyDown (KeyCode.D)) {
StopAllCoroutines ();
StartCoroutine (RightMovement(0f));
}
if (Input.GetKeyDown (KeyCode.A)) {
StopAllCoroutines ();
StartCoroutine (LeftMovement(0f));
}
}
//Movement itself (Right, Left)
IEnumerator RightMovement (float Rloop) {
while (transform.position.x < Time.time * constantspeed + 6) {
speed = 10f;
transform.Translate (speed * Time.deltaTime, 0, 0);
yield return new WaitForSeconds (Rloop);
}
if (transform.position.x > Time.time * constantspeed + 5.9) {
StopAllCoroutines ();
StartCoroutine (LeftMovement (0f));
}
}
IEnumerator LeftMovement (float Lloop) {
while (transform.position.x > Time.time * constantspeed -8) {
speed = -7f;
transform.Translate (speed * Time.deltaTime, 0, 0);
yield return new WaitForSeconds (Lloop);
}
}
}

unity animation error resulting in animations not changing by the parameters

I am working in Unity and trying to create an animation controller that changes the direction the player is facing by playing a different animation while a button is pressed.
I keep getting this error "Assets/Maps/Map1/Entities/Player/PlayerMovement.cs(6,18): warning CS0649: Field PlayerMovement.animator' is never assigned to, and will always have its default valuenull'"
This error does not stop the game from playing, but the animation stays in its default position.
This is the code I have as a player controller which is where I alter the parameters for the animation controller. It tells me the error is on line 6 space 18.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Animator animator;
public float movementSpeed = 100.0f;
public bool Movement = true;
public int Direction = 0;
// Use this for initialization
void Start () {
animator.GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (Movement == true) {
if (Input.GetKey (KeyCode.W)) {
transform.Translate ((Vector2.up) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",0);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate ((-Vector2.right) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",270);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate ((-Vector2.up) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",180);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate ((Vector2.right) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",90);
}
else{
animator.SetInteger("Direction",360);
}
}
}
}
this is an Imgur link to Screen shots of the animator gui for unity. I would have put them directly on this screen, but I don't have the permissions to do that.
Imgur Link
I beleive this is the culprit:
void Start () {
animator.GetComponent<Animator> ();
}
it is not being assinged it should be like this :
void Start ()
{
//you have to use the variable u declared and assing it to the animator
animator = this.GetComponent<Animator> ();
}
hope that solves it.

Categories