2D basic movement UNITY - c#

Currently my character works perfectly on the keyboard, but when I convert your movements to touch, through 3 UI Buttons (i tried UI image too, but success) i'm not succeeding
It basically goes to the right, left, and jumps.
How should do to make it follow these instructions:
When the user presses directional, the character does not stop walking until the user user releases the button, and when you press the jump player jump.
This is the script I use to move through the keyboard!
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float velocity;
public Transform player;
private Animator animator;
public bool isGrounded;
public float force;
public float jumpTime = 0.4f;
public float jumpDelay = 0.4f;
public bool jumped = false;
public Transform ground;
private Gerenciador gerenciador;
// Use this for initialization
void Start ()
{
gerenciador = FindObjectOfType (typeof(Gerenciador)) as Gerenciador;
animator = player.GetComponent<Animator> ();
gerenciador.StartGame ();
}
// Update is called once per frame
void Update ()
{
Move ();
}
void Move ()
{
isGrounded = Physics2D.Linecast (this.transform.position, ground.position, 1 << LayerMask.NameToLayer ("Floor"));
animator.SetFloat ("run", Mathf.Abs (Input.GetAxis ("Horizontal")));
if (Input.GetAxisRaw ("Horizontal") > 0) {
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 0);
}
if (Input.GetAxisRaw ("Horizontal") < 0) {
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 180);
}
if (Input.GetButtonDown ("Vertical") && isGrounded && !jumped) {
// rigidbody2D.AddForce (transform.up * force);
GetComponent<Rigidbody2D> ().AddForce (transform.up * force);
jumpTime = jumpDelay;
animator.SetTrigger ("jump");
jumped = true;
}
jumpTime -= Time.deltaTime;
if (jumpTime <= 0 && isGrounded && jumped) {
animator.SetTrigger ("ground");
jumped = false;
}
}
}
C# if possible, remember i am using Canvas UI for these buttons =]

For the Jump action, what you need is a Button. GameObject->UI->Button. Replace the Image with your own image and click "Set Native Size". Re-size the button to the size that's good for your game.
Attach the Button to the Jump Button slot script below.
public Button jumpButton;
void jumpButtonCallBack()
{
// rigidbody2D.AddForce (transform.up * force);
GetComponent<Rigidbody2D>().AddForce(transform.up * force);
jumpTime = jumpDelay;
animator.SetTrigger("jump");
jumped = true;
}
void OnEnable(){
//Un-Register Button
jumpButton.onClick.AddListener(() => jumpButtonCallBack());
}
void OnDisable(){
//Un-register Button
jumpButton.onClick.RemoveAllListeners();
}
For the Left and Right Movement buttons,you should not use Button component for them like the jump button. You have to implement Virtual JoyStick to make it look realistic. Unity have Assets called CrossPlatformInputManager that can do that. You have to import it and modify it a little bit in order to use it. Watch this to understand how to import it.
Now, you can replace your Input.GetAxis and Input.GetAxisRaw functions with CrossPlatformInputManager.GetAxis("Horizontal") and CrossPlatformInputManager.GetAxisRaw("Horizontal").
If you get it to work, then can use below to make your code comptible with both mobile and desktop.
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL
//put your Input.GetAxis` and `Input.GetAxisRaw` code here
#elif UNITY_ANDROID || UNITY_IOS
//Put your `CrossPlatformInputManager.GetAxis("Horizontal")` and `CrossPlatformInputManager.GetAxisRaw("Horizontal")`. here
#endif

I think you should use EventTrigger OnPointerDown and OnPointerUp events:
http://docs.unity3d.com/ScriptReference/EventSystems.EventTrigger.html
I hope it helps you

Related

Disable diagonal following of player

So I have a script for my player where I have disabled diagonal move. I then created a script for his dog companion that follows him in the world and it's almost perfected except when I do a direction change from left/right to up/down or vice versa the dog will follow at a diagonal and looks really weird since there is no animations and he basically slides there. I tried to disable diagonal like how I did for the player but it doesn't work. Is there a way to go about this or would it be better to just add in a diagonal animation for just the dog?
public class Bowser : MonoBehaviour
{
public float speed;
private Transform target;
private Vector2 move;
private Animator anim;
private void Awake()
{
anim = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
move.x = Input.GetAxisRaw("Horizontal");
move.y = Input.GetAxisRaw("Vertical");
if (Vector2.Distance(transform.position, target.position) > 1.5)
{
// Code attempt to get rid of diagonal movement
if (move.x != 0) move.y = 0;
if (move != Vector2.zero)
{
anim.SetFloat("moveX", move.x);
anim.SetFloat("moveY", move.y);
anim.SetBool("moving", true);
}
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
else
anim.SetBool("moving", false);
}
}
Instead of just checking for 0 you could just use the bigger value
if (Mathf.Abs(move.x) > (Mathf.Abs(move.y)) move.y = 0;
else move.x = 0;
it would be better if you just provided diagonal animations for the dog
Thanks for the advice in the end I found that it became a smoother transition to just add this
if (Mathf.Abs(move.x) > .01f)
targetPosition.y = transform.position.y;
if (Mathf.Abs(move.y) > .01f)
targetPosition.x = transform.position.x;
and then change all my target.Position to the targetPosition

How can I make this unity movement script work?

How can I make this script work, or another alternative player movement script? This basic movement script in Unity doesn't do anything when i press WASD for some reason. I am a beginner at C# and unity and I kind of need an alternative player movement script that actually works.
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
transform.Translate(Vector3.forward);
if (Input.GetKeyDown(KeyCode.S))
transform.Translate(Vector3.back);
if (Input.GetKeyDown(KeyCode.A))
transform.Translate(Vector3.left);
if (Input.GetKeyDown(KeyCode.D))
transform.Translate(Vector3.right);
I recommend using the GetAxis("Horizontal") and GetAxis("Vertical") methods which maps wasd and arrow keys by default to help slim down your big if tree.
Below is a small example from an old unversity project of mine.
Note: the "* speed * Time.deltaTime" as this is used to help translate as time/frames move on, speed is just a multiplier in this case.
public float speed = 10.0f;
private float translation;
private float straffe;
// Use this for initialization
void Start()
{
// turn off the cursor
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
// Input.GetAxis() is used to get the user's input
// You can further set it on Unity. (Edit, Project Settings, Input)
translation = Input.GetAxis("Vertical") * speed * Time.deltaTime;
straffe = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.Translate(straffe, 0, translation);
if (Input.GetKeyDown("escape"))
{
// turn on the cursor
Cursor.lockState = CursorLockMode.None;
}
}
Input.GetKeyDown checks if you pressed the w key on that frame. You need Input.GetKey. That checks if you are holding
You should use GetAxis("Horizontal") & GetAxis("Vertical");
Here is my basic code for my projects default movement:
//movement
Rigidbody rb;
float xInput;
float yInput;
public float speed;
public float defSpeed;
public float sprint;
public bool isGrounded = true;
public float jump;
// Start is called before the first frame update
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
xInput = Input.GetAxis("Horizontal");
yInput = Input.GetAxis("Vertical");
//Things is still can't understand
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
float cameraRot = Camera.main.transform.rotation.eulerAngles.y;
rb.position += Quaternion.Euler(0, cameraRot, 0) * input * speed * Time.deltaTime;
//sprint
if (Input.GetKeyDown(KeyCode.LeftShift))
{
speed = sprint;
}
else if (Input.GetKeyUp(KeyCode.LeftShift))
{
speed = defSpeed;
}
//jump
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
rb.AddForce(0, jump, 0);
//Debug.Log("Jump!");
}
Hope this helps:)

Moving Object Not Stopping On Collision Unity

I am developing an infinite tower jumping game using Unity2D, and currently working on a continually moving object which causes the player to die if contact is made. The player can also die if they either fall off of a platform or off-screen. All methods of death rely on a BoxCollider2D I am using as a Killbox (tagged accordingly) - the player sprite has a RigidBody2D and BoxCollider2D attached to it - so there is one attached to the main camera (it moves as the player sprite progresses through the level) and to the top of the moving object.
The current code I have works up to the point where the game over screen appears on player death, but the object continues to move whilst everything else stops.
Here is my code for the moving object:
public class Water : MonoBehaviour {
private Collider2D playerCollider;
public ControllerNew thePlayer;
private float speed = 2f;
public GameManager theGameManager;
//reference scoremanager
private ScoreManager theScoreManager;
bool shouldMove = true;
// Start is called before the first frame update
void Start()
{
theScoreManager = FindObjectOfType<ScoreManager>();
thePlayer = FindObjectOfType<ControllerNew>();
lastPlayerPosition = thePlayer.transform.position;
}
// Update is called once per frame
void Update()
{
if (shouldMove = true)
{
transform.position += Vector3.up * speed * Time.deltaTime;
if (theScoreManager.scoreCount > 100 && shouldMove)
{
transform.position += Vector3.up * (speed+1) * Time.deltaTime;
}
if (theScoreManager.scoreCount > 250 && shouldMove)
{
transform.position += Vector3.up * (speed +2) * Time.deltaTime;
}
if (theScoreManager.scoreCount > 500 && shouldMove)
{
transform.position += Vector3.up * (speed+4) * Time.deltaTime;
}
if (theScoreManager.scoreCount > 1000 && theScoreManager.scoreCount > theScoreManager.hiScoreCount && shouldMove)
{
transform.position += Vector3.up * (speed+5) * Time.deltaTime;
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player New")
{
transform.position += Vector3.zero * (speed * 0) * Time.deltaTime;
}
//call object by its tag
if (other.gameObject.tag == "Killbox")
{
shouldMove = false;
if (shouldMove = false){
theGameManager.RestartGame();
transform.position += Vector3.zero * (speed * 0) * Time.deltaTime;
}
}
}
Edit (Issue resolved)
So it turns out that after adding the Water.StopMoving() method into my controller script, the water had not been called as a GameObject in void Start(). Once this was added, the water object stopped on collision.
Just want to say thank you #D.B for your help and bearing with me - apologies if the info I gave wasn't everything you needed to be able to assist me
You made a mistake on the first line of the Update() method :
if (shouldMove = true)
You set the bool to true, not comparing it. Use double = otherwise it will set the bool to true at every frame.
if (shouldMove == true)
By the way you can simplify this part :
//call object by its tag
if (other.gameObject.tag == "Killbox")
{
shouldMove = false;
theGameManager.RestartGame();
transform.position += Vector3.zero * (speed * 0) * Time.deltaTime;
}
(You forgot a = too)
I made a test with this simplified script
void Update()
{
if (shouldMove == true)
{
Debug.Log("move");
transform.position += Vector3.up * speed * Time.deltaTime * GetDifficultyFactor();
}
}
private float GetDifficultyFactor()
{
float factor = 1f;
if(theScoreManager.scoreCount > 100)
{
factor += 1f;
}
if (theScoreManager.scoreCount > 250)
{
factor += 2f;
}
// Add all your speed modification condition here
return factor;
}
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("trigger");
//call object by its tag
if (other.gameObject.tag == "Killbox")
{
Debug.Log("die");
shouldMove = false;
}
}
And it work fine. Are you sure you have a collider2D set to trigger on your charactert with the tag "Killbox" (with the first letter in uppercase ?). You should have a rigidbody2d on the character too.
Mistake come frome another part of your code or with some trouble with collider2D/tag/RigidBody2D. Without seeing all it's difficult to help you more.
You should try to add some Debug.Log() or use debugeur with breakpoint to be sure code enter into your "die" statement and then not going on the Update if statement. If yes, it's mean you probably set the shouldMove variable in another part of your script.
Answer regarding discussion in comments
I think you want to make this OnTriggerEnter2D logic in both script.
Without seeing all your project I suggest you to make a reference bewteen your character and your water script. Then when the player die the player script will call a method on water to stop it.
public class Player : MonoBehaviour
{
public Water Water;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Killbox")
{
Debug.Log("die");
Water.StopMoving();
}
}
}
public class Water : MonoBehaviour
{
private bool shouldMove;
public void Update()
{
...
}
public void StopMoving()
{
shouldMove = false;
}
// No Trigger logic here
}

How do I delay an animation using my character movement script?

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.

Make ball Jumping

I am trying to make a script where i can move a ball, horizontal and vertical. I managed to get that working.
But now I want to make my ball "jump". I ended with script below, but now my ball just get launched like a rocket xD
Can anyone help me out
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpSpeed;
public GUIText countText;
public GUIText winText;
private int count;
void Start()
{
count = 0;
SetCountText();
winText.text = " ";
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);
Vector3 jump = new Vector3 (0, jumpSpeed, 0);
GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);
if (Input.GetButtonDown ("Jump"));
GetComponent<Rigidbody>().AddForce (jump * jumpSpeed * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "PickUp") {
other.gameObject.SetActive(false);
count = count +1;
SetCountText();
}
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
if (count >= 10)
{
winText.text = "YOU WIN!";
}
}
}
Jumping does not work with adding a continuous force on an object. You will have to apply a single impulse to the object once when the jump button is first pressed. This impulse will also not include a time factor, because it is applied only once. So you would get something like this:
bool jumping;
if (Input.GetButtonDown ("Jump") && !this.jumping);
{
GetComponent<Rigidbody>().AddForce (jumpForce * new Vector3(0,1,0));
this.jumping = true;
}
Also note that in your example you are multiplying the upward unit vector by the jumpspeed twice. Once in the jump vector initialization and then once in the AddForce method.
Of course, you will also have to make sure that gravity applies to pull the object back down (and if the object hits the ground, reset the jump bool.
In general, depending on what kind of game you are making, it is easier to just set the velocity of the object yourself and don't work with the Unity physics engine to do some simple moving around.
There is an error in your code in the function FixedUpdate:
if (Input.GetButtonDown ("Jump"));
in that way you are applying a force on your object at every frame because the semicolon is excluding the row below from the condition. By removing the semicolon you will have a correct if implementation in case of a jump, as long as on your RigidBody component UseGravity is enabled.
if (Input.GetButtonDown ("Jump"))
GetComponent<Rigidbody>().AddForce (jump * jumpSpeed * Time.deltaTime);
Hope it helps.
Thanks everyone, it was a great help. I now have a jumping character. One who can only jump when grounded.
public bool IsGrounded;
void OnCollisionStay (Collision collisionInfo)
{
IsGrounded = true;
}
void OnCollisionExit (Collision collisionInfo)
{
IsGrounded = false;
}
if (Input.GetButtonDown ("Jump") && IsGrounded)
{
GetComponent<Rigidbody>().velocity = new Vector3(0, 10, 0);
}

Categories

Resources