Reputation: 48
I'm a newbie. It's a very simple doubt yet I don't know how to. I wanna make my character jump forward by 1.And the animation I have here is Inplace (He goes up in y and comes down back).So i have to move my character forward programmatically while playing the animation and it should look smooth. So this is the script I have attached to my character.
if(Input.GetKeyDown(KeyCode.Space))
{
this.gameObject.GetComponent<Animator>().SetTrigger("shouldJump?");
transform.position += 1*transform.forward;
}
But what's happening to me is he is going forward by 1 and then playing the JumpAnimation. Please Help!!
Upvotes: 0
Views: 516
Reputation: 2197
What you're doing here is setting the characters position one unit forward in the z-axis and telling animator to start jump animation each time player presses the space button. To move transform in span of multiple frames you'll have to either gradually modify the position in the update method or use the physics engine.
You can check Unify community wiki for some examples or go through some of the many tutorials on player movement in Unity.
From the wiki:
RigidBody
and Collider
(CapsuleCollider
, SphereCollider
or BoxCollider
)// From: http://wiki.unity3d.com/index.php/RigidbodyFPSWalker
// Creative Common's Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0).
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
[RequireComponent (typeof (CapsuleCollider))]
public class CharacterControls : MonoBehaviour {
public float speed = 10.0f;
public float gravity = 10.0f;
public float maxVelocityChange = 10.0f;
public bool canJump = true;
public float jumpHeight = 2.0f;
private bool grounded = false;
void Awake () {
rigidbody.freezeRotation = true;
rigidbody.useGravity = false;
}
void FixedUpdate () {
if (grounded) {
// Calculate how fast we should be moving
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= speed;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
// Jump
if (canJump && Input.GetButton("Jump")) {
rigidbody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
}
}
// We apply gravity manually for more tuning control
rigidbody.AddForce(new Vector3 (0, -gravity * rigidbody.mass, 0));
grounded = false;
}
void OnCollisionStay () {
grounded = true;
}
float CalculateJumpVerticalSpeed () {
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * jumpHeight * gravity);
}
}
Upvotes: 1