i have a simple script that should animate my player but its not working. i read forums for a while, some had issues about animation legacy option and i fixed it, but my character still doesn't animate, and there isn't any compiling errors. Here is my script:
using UnityEngine;
using System.Collections;
public class maincharacter : MonoBehaviour {
void Start () {
}
float xSpeed = 10f;
float zSpeed = 10f;
public float playerMovementSpeed = 10f;
void Update () {
float deltaX = Input.GetAxis ("Horizontal") * xSpeed;
float deltaZ = Input.GetAxis ("Vertical") * zSpeed;
Vector3 trans = new Vector3 (deltaX + deltaZ ,0f,deltaZ - deltaX);
transform.Translate (trans.normalized * Time.deltaTime * playerMovementSpeed, Space.World);
animation.Play ("mcrunsw");
/*if (deltaX != 0 || deltaZ != 0) {
animation.Play ("mcrunsw");
}*/
}
}
Here is my gameObject and animation:
Any help would be appreciated. Thanks in advance.
From the manual:
Play() will start animation with name animation, or play the default
animation. The animation will be played abruptly without any blending.
Since you call this every frame, I'd suppose it will just show the first frame of the animation and then be stopped by the next animation.Play in the next Update. Try this:
if (!animation.isPlaying) {
animation.Play();
}
In general, I would suggest using Mechanim for character animations.
Another viable option along with the solution above is CrossFadeQueued.
You just simply use the function below and it'll seamlessly CrossFade.
usage is PlayAnimation("mcrunsw");
function PlayAnimation(AnimName : String) {
if (!animation.IsPlaying(AnimName))
animation.CrossFadeQueued(AnimName, 0.3, QueueMode.PlayNow);
}
Related
I'm writing movement for my space game and spaceship object (player) with mouse cursor.
Currently have following code:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Move : MonoBehaviour {
public float speed = 1.5f;
public float rotationSpeed = 90f;
public float rotPrecision = 0.1f;
public float movePrecision = 0.1f;
private Vector3 pos;
private Quaternion qTo;
void Start () {
pos = transform.position;
qTo = transform.rotation;
}
void Update () {
if (!EventSystem.current.IsPointerOverGameObject())
{
if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0))
{
pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
}
var dir = pos - transform.position;
qTo = Quaternion.LookRotation(Vector3.forward, pos - transform.position);
if (Quaternion.Angle(transform.rotation, qTo) >= rotPrecision) //just set your own precision
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, Time.deltaTime * rotationSpeed);
if (Vector3.Distance(transform.position, pos) > movePrecision) // 0.1f
transform.Translate(Vector3.up * speed * Time.deltaTime);
}
}
}
But there i have the problem with the movement precision and rotation when the point is too close to player (have infinite loop).
The idea of this movement system described with the following image:
(Player actor is green, path is gray, and destination point is red).
I hope that somebody could help me w/ that.
Thank you!
If I understand your question correctly, the problem is that the player's movement never stops as the code can't reach a finishing point.
To solve this you can add an acceptable precision margin.
So calculate if the difference between the rotation you wish or the movement you wish, and the players actual rotation/position, is less than a given variable, for example less than 0.05%.
That way you could allow the program to know that if it's just within 0.05% precision, then it's okay for it to stop moving.
Otherwise, if the program never reaches a complete and perfect rotation and position, it will continue to adjust endlessly due to slight mathematical imprecision in the calculations and movement pattern.
I am trying to allow the player, in a pong game, to control both paddles. However, for some reason only one paddle is controllable while the other simply does nothing. Here is an image of the paddle property bar.
And here is the code to the right most paddle that should be controlled with arrow keys.
using UnityEngine;
using System.Collections;
public class PaddleRight : MonoBehaviour
{
public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp;
void Start()
{
}
// Update is alled once per frame
void Update()
{
float yPos = gameObject.transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow)) {
playerPosR = new Vector3(gameObject.transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
print("right padddle trying to move");
}
gameObject.transform.position = playerPosR;
}
}
I can't seem to figure out anywhere why it won't move.. Please, any help would be awesome because I have checked everywhere at this point. Thanks!
I recreated the problem in a project and found that the only problem with it might be you forgetting that the yClamp is public and its set to 0 in the inspector. Make sure you set yClamp to whatever it should be instead of 0.
I would suggest moving the yPos assignment as well as setting the position inside the if statement as you arent changing those if the player isnt moving.
You can also change gameObject.transform.position to just plain transform.position
here is the refined code:
public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp; // make sure it's not 0 in the inspector!
// Update is alled once per frame
void Update()
{
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow))
{
float yPos = transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);
playerPosR = new Vector3(transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
transform.position = playerPosR;
}
}
Ive been trying to make this Object move forward on its own and turn left or right in circular fashion if the left/right keys are pressed with unity using C#, this picture will make it clearer: http://prnt.sc/avmxbn
I was only able to make it move on its own and this is my code so far:
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
Update(){ transform.localPosition += transform.forward *speed *Time.deltaTime
float speed = 5.0f;
// Use this for initialization
void Start () {
Debug.Log ("it's working?");
}
// Update is called once per frame
void Update () {
transform.localPosition += transform.forward * speed * Time.deltaTime;
}
void FixedUpdate(){
}
}
I have no idea, however, how to change left or right directions in circular paths like the picture linked demonstrates. Anyone able to help me? Thank you.
There are obvious errors in your code. You call Update() twice. The first time without a return type. You shouldn't do that. Start by deleting the first Update() and the code on the same line.
Then to answer your question you will have to look into getting input from the user. Use Input.GetKey() and pass it a KeyCode value such as KeyCode.Afor the 'A' key. So you can say:
if(Input.GetKey(KeyCode.A))
{
//do something(for example, Turn the player right.)
}
Then look into rotating the object using transform.Roate to rotate the player.
Attach this script to your moving object:
using UnityEngine;
public class MoveController : MonoBehaviour {
float angle = 1F;
float speed = 0.2F;
void Update ()
{
if ( Input.GetKey (KeyCode.LeftArrow) )
transform.Rotate(Vector3.up, -angle);
else if( Input.GetKey (KeyCode.RightArrow) )
transform.Rotate(Vector3.up, angle);
transform.Translate(Vector3.forward * speed);
}
}
The key point here is to separate your moving from your rotating functionality.
You can use this script for movement :
using UnityEngine;
public class MovementController : MonoBehaviour {
public Rigidbody rigidbody;
float angle = 0f;
const float SPEED = 1f;
float multiplier = 1f;
void FixedUpdate(){
if ( Input.GetKey (KeyCode.LeftArrow) )
angle -= Time.deltaTime * SPEED * multiplier;
else if( Input.GetKey (KeyCode.RightArrow) )
angle += Time.deltaTime * SPEED * multiplier;
rigidbody.velocity = new Vector2(Mathf.Sin(angle) * SPEED, Mathf.Cos(angle) * SPEED);
}
}
Multiplier value is inversely proportional to the radius.
Ive been trying to make this Object move forward on its own and turn left or right in circular fashion if the left/right keys are pressed with unity using C#, this picture will make it clearer: http://prnt.sc/avmxbn
I was only able to make it move on its own and this is my code so far:
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
Update(){ transform.localPosition += transform.forward *speed *Time.deltaTime
float speed = 5.0f;
// Use this for initialization
void Start () {
Debug.Log ("it's working?");
}
// Update is called once per frame
void Update () {
transform.localPosition += transform.forward * speed * Time.deltaTime;
}
void FixedUpdate(){
}
}
I have no idea, however, how to change left or right directions in circular paths like the picture linked demonstrates. Anyone able to help me? Thank you.
There are obvious errors in your code. You call Update() twice. The first time without a return type. You shouldn't do that. Start by deleting the first Update() and the code on the same line.
Then to answer your question you will have to look into getting input from the user. Use Input.GetKey() and pass it a KeyCode value such as KeyCode.Afor the 'A' key. So you can say:
if(Input.GetKey(KeyCode.A))
{
//do something(for example, Turn the player right.)
}
Then look into rotating the object using transform.Roate to rotate the player.
Attach this script to your moving object:
using UnityEngine;
public class MoveController : MonoBehaviour {
float angle = 1F;
float speed = 0.2F;
void Update ()
{
if ( Input.GetKey (KeyCode.LeftArrow) )
transform.Rotate(Vector3.up, -angle);
else if( Input.GetKey (KeyCode.RightArrow) )
transform.Rotate(Vector3.up, angle);
transform.Translate(Vector3.forward * speed);
}
}
The key point here is to separate your moving from your rotating functionality.
You can use this script for movement :
using UnityEngine;
public class MovementController : MonoBehaviour {
public Rigidbody rigidbody;
float angle = 0f;
const float SPEED = 1f;
float multiplier = 1f;
void FixedUpdate(){
if ( Input.GetKey (KeyCode.LeftArrow) )
angle -= Time.deltaTime * SPEED * multiplier;
else if( Input.GetKey (KeyCode.RightArrow) )
angle += Time.deltaTime * SPEED * multiplier;
rigidbody.velocity = new Vector2(Mathf.Sin(angle) * SPEED, Mathf.Cos(angle) * SPEED);
}
}
Multiplier value is inversely proportional to the radius.
I am fairly new to unity development. I want to find out why when I move a sprite object, it is causing very noticeable jitter. I have read quiet some answers on the internet, some say things about rigidbody2d, some about fixed or late update etc etc. But my problem does not seem to be solved by any of those. I just have a sprite object, no rigidbody, just a gameobject with sprite renderer component and a script attached to it in an empty project containing a camera ofcourse. Here is the whole script I am using, you can just copy paste into a cs file named MoveBackground and it will work.
using UnityEngine;
using System.Collections;
public class MoveBackground : MonoBehaviour {
Vector3 pointA;
Vector3 pointB;
float timeRequired;
public float speed = 5;
IEnumerator movingEnum;
float belowEdge;
// Use this for initialization
void Start () {
Camera cam = Camera.main;
float height = 2f * cam.orthographicSize;
belowEdge = cam.transform.position.y - height/2f;
movingEnum = StartMoving ();
initializeAndMoveObject ();
}
// Update is called once per frame
void Update () {
// transform.Translate(0, (-1*speed * Time.deltaTime) / 100, 0);
//this.gameObject.transform.Translate (0f , Time.deltaTime * speed,0f);
}
void MoveToNextPosition()
{
float distance = Mathf.Abs( Mathf.Sqrt (Mathf.Pow ((pointA.x - pointB.x), 2f) + Mathf.Pow ((pointA.y - pointB.y), 2f)));
float time = distance/speed;
timeRequired = time;
movingEnum.MoveNext ();
}
IEnumerator StartMoving()
{
while (true) {
yield return StartCoroutine(MoveObject(transform, pointA, pointB, timeRequired));
}
}
IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time)
{
var i= 0.0f;
var rate= 1.0f/time;
while (i < 1.0f) {
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
yield return null;
}
}
public void initializeAndMoveObject()
{
Vector3 moveTowardsPoint;
SpriteRenderer sR = GetComponent<SpriteRenderer> ();
Vector3 bounds = sR.bounds.extents;
float height = bounds.y * 2f;
moveTowardsPoint = transform.position;
moveTowardsPoint.y = belowEdge - height / 2f;
pointA = transform.position;
pointB = moveTowardsPoint;
MoveToNextPosition ();
}
}
This script moves the object from top to bottom. Also, I dont have an jitter when I run it on my computer in editor. But when I run it on device (iPhone6+) , it causes very very big annoying jitter, constantly, depending on how fast it is moving down.
This is not the only method I have tried to make an object move, I have tried using
transform.Translate(0, (-1*speed * Time.deltaTime) / 100, 0);
in update and fixedupdate to no avail. I have tried using Quad for this purpose. (My gameobject just basically is a Bg that moves down). Piece of code for quad script is
public float speed = -0.5f;
private Vector2 savedOffset;
void Start () {
savedOffset = renderer.sharedMaterial.GetTextureOffset ("_MainTex");
}
void Update () {
float y = Mathf.Repeat ((Time.time * speed), 1);
Vector2 offset = new Vector2 (savedOffset.x, y);
renderer.sharedMaterial.SetTextureOffset ("_MainTex", offset);
}
void OnDisable () {
renderer.sharedMaterial.SetTextureOffset ("_MainTex", savedOffset);
}
If some one can guide me, I would be very thank full to you.
This issue for me was solved by setting the targetFrameRate in the code to 60 for iPhone6+(setting 30 didnt work, setting -1 didnt work), any value above 60 works too but below 60 was causing jittering. So all I changed was, I had to execute this statement once my app started (Anywhere in the code will work but preferably Awake, in my scenario it didnt had to be in Awake).
Application.targetFrameRate = 60;
Unity documentation reference : http://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html
Just a side note, not all devices require 60 framerate.