Adding velocity to 2d sprite in c# unity - c#

hi i was wondering if someone could help me fix practice code (i make practice codes before i make the real thing because its just how i roll) it is basically an object that requires the user to click on the screen in order for it to not touch the ground much like flappy bird however although i have applied gravity correctly to the sprite i cannot fix the velocity section (i coded is to every time the user clicks with his mouse or taps the space key the object will move up like flappy bird)
using UnityEngine;
using System.Collections;
public class BirdMovment : MonoBehaviour {
Vector3 Velocity = Vector3.zero;
public Vector3 gravity;
public Vector3 flapVelocity;
public float maxSpeed = 5f;
bool didFlap = false;
// Use this for initialization
void Start () {
}
void update (){
if (Input.GetKeyDown (KeyCode.Mouse0))
{
didFlap = true;
}
}
// Update is called once per frame
void FixedUpdate () {
Velocity += gravity* Time.deltaTime;
if (didFlap) {
didFlap = false;
Velocity += flapVelocity;
}
Velocity = Vector3.ClampMagnitude (Velocity, maxSpeed);
transform.position += Velocity * Time.deltaTime;
}
}
can you please fix the error as every time i set the velocity in unity for the sprite ad run the program the sprite just keeps on falling and no matter how much i click or tap the space key the sprite does not stop falling even if i increase the velocity

First of all, the correct Update function is with a capital U, so Update() instead of update(). Then, since you're not doing anything with physics, you can do everything in Update and not use FixedUpdate at all. So you can remove the didFlap variable and add to Velocity directly inside the if (Input.GetKeyDown ...) block. Furthermore, regarding gravity, you're multiplying it twice with Time.deltaTimethere, so remove the first one. That should get you started.

Related

Update breaks function in Unity

I have the following code
public Rigidbody2D rb;
public float speed = 5f;
void FixedUpdate()
{
if (Input.GetKeyDown("w"))
{
Fire();
}
}
void Fire()
{
rb.MovePosition(rb.position + Vector2.down * speed * Time.deltaTime);
}
but every time I play the game, the ball does not move according to the fire function, it only goes down by 1 on the y-axis.
How can I edit my code, so that the Rigidbody moves according to the Fire() function?
There could be a couple things going wrong here. The first thing that stands out to me is that you're using Input.GetKeyDown instead of Input.GetKey-- GetKeyDown only returns true on the first frame that the key is pressed (so it's useful for things like shooting once per keypress), whereas GetKey returns true for the entire time that the key is down (so it's useful for things like movement). Changing that should give you the behavior that you're expecting.
Another issue is that you're doing input checking in FixedUpdate. It runs on a separate game loop from Update, and you can find more details about that here: Is it really wrong to use Input.GetKey() on FixedUpdate?
I would use Input and GetKey to store the input state in a Vector2 in the Update loop, and then use that data in FixedUpdate to do the actual movement:
public Rigidbody2D rb;
public float speed = 5f;
private Vector2 velocity = Vector2.zero;
void Update()
{
if (Input.GetKey("w"))
{
velocity = Vector2.down * speed;
}
else {
velocity = Vector2.zero;
}
}
void FixedUpdate()
{
MoveBall();
}
void MoveBall()
{
rb.MovePosition(rb.position * velocity * Time.deltaTime);
}
This way, you also have a stronger separation between the input code and movement code, and it will be easier to handle once you start trying to implement more complexity. Good luck!

Input.GetAxis for android

I'm creating a maze game and curently i am having delays with my android controls. I have lade the computer controls to move front and to turn left and right and to jump using input.getaxis. Now on android i created buttons that work but not how i want. It can jump and turn how i want but it doesnt move properly. There are 2 problems one is that when i click it moves a bit and then i need to click again but i want to hold and it will move continuously and second problem is that when i turn the character doesnt move the corect way it goes always on x axis with input.getaxis everything works perfectly but i need something that will work for androdid like that, here is my code:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speed;
public float speedj;
Rigidbody rb;
static Animator anim;
void Start()
{
rb = GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
}
public void Walk ()
{
anim.SetTrigger ("Walk");
rb.velocity = new Vector3 (0,0,7f);
}
public void Left ()
{
transform.Rotate(0,-90f,0);
}
public void Right ()
{
transform.Rotate(0,90f,0);
}
public void Jump ()
{
anim.SetTrigger ("Jump");
rb.velocity = new Vector3 (0,4f,0);
}
public void StopVelocity ()
{
rb.velocity = Vector3.zero;
transform.Translate(0,0,0);
}
void FixedUpdate ()
{
float x = Input.GetAxis ("Horizontal") * Time.deltaTime * speed;
float z = Input.GetAxis ("Vertical") * Time.deltaTime * speed;
transform.Translate (0,0,z);
transform.Rotate (0,x,0);
if(Input.GetKey(KeyCode.Space))
{
anim.SetTrigger ("Jump");
rb.velocity = new Vector3 (0,speedj,0);
}
}
}
So this is it the fixedUpdate functionis for the computer the others are for buttons for android i am using event trigger for pointer up and down events pleasehelp me to change the code so that it will work for android like it works with Input.getAxis for computer thanks!
"when i click it moves a bit and then i need to click again but i want to hold and it will move continuously."
Using the EventTrigger here should be the optimal way. Check out OnPointerDown(); the function should be called for every frame. You should attach the EventTrigger to the button for it to work on mobiles.
"when i turn the character doesnt move the corect way."
Try moving using your Local Transforms Forward. Namely Transform.Forward(). It will allow you to move forward into the direction you set before, the Forward is always a Normalized Vector3. Moving in the way you are will use the world axis, your rotation wont matter at all.

2D Unity Enemy Chase/Evade script in C#

Okay so I've been fighting with this script for a couple days now. I've made progress in other aspects but I can't seem to get my enemies to properly chase the player character.
The script is supposed to have the enemies wander until an empty child 'eyes' sees the player. Then it should start chasing the player. Think pac-man. What it's doing right now is making one loop of it's wander cycle and then stopping and not seeing the player at all.
This is the code that I've got so far for that script -
using UnityEngine;
using System.Collections;
public class dudeFollow : MonoBehaviour {
Transform tr_Player;
float f_MoveSpeed = 3.0f;
private DudeMove moveScript;
public Transform eyes;
public float sightRange = 3f;
// Use this for initialization
void Start () {
tr_Player = GameObject.FindGameObjectWithTag("Player").transform;
moveScript = GetComponent<DudeMove>();
}
// Update is called once per frame
void Update () {
RaycastHit hit;
if (Physics.Raycast (eyes.transform.position,eyes.transform.forward, out hit,sightRange) && hit.collider.CompareTag ("Player")) {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
moveScript.enabled = false;
}
}
}
Any help or tips would be appreciated.
Because you have 2D game, what most likely happens is your enemy wonders away on z-axis as well, but because it's 2D, you can't see it. So switch to 3D mode in your main scene window and see if that's the case.
If it is, just reset z-axis to 0 on every frame and disable angular momentum :) I had this happen with 2D games.
void Update () {
RaycastHit hit;
if (Physics.Raycast (eyes.transform.position,eyes.transform.forward, out hit,sightRange) && hit.collider.CompareTag ("Player")) {
transform.position += transform.forward * f_MoveSpeed * Time.deltaTime;
moveScript.enabled = false;
}
transform.position.z = 0; // or something along those lines, I don't remember the syntax exactly.
}

Player stops moving upon contact with a gameObject

I am having my player constantly drop downwards on the screen and when the player interact with other gameobjects, I want to destroy those gameobjects and want the player to carry on dropping.
But the moment the player hits the other gameobject, the gameobject does gets destroyed but the player stops dropping. Please help advice what I am doing wrong.
//Script attached to player:
//x-axis movement speed
public float playerMoveSpeed = 0.2f;
//how much force to act against the gravity
public float upForce = 9.0f;
//horizontal control
private float move;
// Update is called once per frame
void Update()
{
//player left right x-axis movement control
move = Input.GetAxis("Horizontal") * playerMoveSpeed;
transform.Translate(move, 0, 0);
}
void FixedUpdate()
{
//to fight against the gravity pull, slow it down
rigidbody.AddForce(Vector3.up * upForce);
}
//Script attached to gameObject to be destroyed on contact with player
void OnCollisionEnter(Collision col)
{
//as long as collide with player, kill object
if (col.gameObject.tag == "Player")
{
Destroy(gameObject);
}
}
First one should solve your problem, the second one might make your life easier :)
1.) Mark the objects as "Triggers" so that no real collision happens. That way your player should just fall through and keep its speed. You also need to use OnTriggerEnter instead of OnCollisionEnter
2.) If you dont really need "forces" but just want to move the player constantly you could just turn off gravity and set rigidbody.velocity manually like(i am assuming 2d here):
void FixedUpdate()
{
horizontalVelocity = Input.GetAxis("Horizontal") * playerMoveSpeed;
rigidbody.velocity = new Vector3(horizontalVelocity, verticalVelocity, 0.0f);
}
Just play around with values for verticalVelocity and horizontalVelocity untill it feels right.
Also note that if you move something in Update() you should probably multiply the translation with Time.deltaTime or your player will move faster on higher fps. FixedUpdate is called in fixed time intervalls so you dont need it there(thats why its called Fixed Update).

Unity Jump function issue

I've been working on this script for the past day. For some reason my character will not jump as long as it's animator is active. I've got into the animation (there is only one) and removed all references to the animation placing a position anywhere and still the issue presides.
I have discovered that I can make my player jump if I use Co-routine which I'm using. However, I'm still new to using them and I can't work out why my player won't fall to the ground once a force has been added to it. And my player only moves up when the button is clicked. Could someone please take a look at my script and tell me what I'm doing wrong?
public float jumpSpeed = 100.0f;
public float jumpHeight = 2.0f;
public AudioClip jumpSound;
private GameObject pos;
private bool moving;
private bool isJumping;
void Start()
{
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonDown(0))// && !moving)
{
isJumping = true;
StartCoroutine(JumpPlayer(gameObject.transform.localPosition));
}
else
{
isJumping = false;
}
}
IEnumerator JumpPlayer(Vector3 startPos)
{
Vector3 jump = new Vector3(transform.localPosition.x, jumpHeight, transform.localPosition.z);
float t = 0f;
t += Time.deltaTime / jumpSpeed;
rigidbody.AddForce(Vector3.up * jumpSpeed);
//gameObject.transform.localPosition = Vector3.Lerp(startPos, jump, 0.5f);
//isJumping = false;
yield return null;
}
Firstly, your use of coroutine isn't doing anything in particular - because it only does yield return null at the end, it'll run in a single frame and then exit. You could make it a regular void function and you shouldn't see any change in behaviour.
Removing other redundant code and you have just this:
if(Input.GetMouseButtonDown(0))
{
rigidbody.AddForce(Vector3.up * jumpSpeed);
}
This force is added for only a single frame: the frame where the mouse button is pressed down (if you used Input.GetMouseButton instead, you'd see the force applied for multiple frames).
You say "my player only moves up when the button is clicked" but I'm not clear why that's a problem - perhaps you mean that the player should continue to move up for as long as the button is held, in which case you should refer to my previous paragraph.
The most obvious reasons for the player not falling again are related to the RigidBody component: do you have weight & drag set to suitable values? An easy way to test this would be to position your player some distance from the ground at the start of the scene, and ensure that they fall to the ground when you start the scene.
Another reason might be that you're using the default override of .AddForce in an Update cycle. The default behaviour of this method applies force during the FixedUpdate calls, and you might find that using ForceMode.Impulse or ForceMode.VelocityChange gives you the result you're looking for.

Categories

Resources