Move GameObject with Sprite Renderer animation - unity3d

I have an object in which I have added a sprite Render and an animation to see a sprite sheet in motion, the fact is that I want this object to move from one position to another. But I don't understand why it doesn't work.
The first thing I do with this object is to instantiate it to make a clone.
Then in the update I do the following:
Method void:
spriteRenderer = throwObject.spriteRenderer;
GameObject spriteRendererObject = Instantiate(spriteRenderer);
Update:
if(_animationStarted2){
Vector3 startPos = transform.position;
Vector3 targetPos = _targetPos;
spriteRenderer.transform.position = Vector3.MoveTowards(startPos, Vector3.Lerp(startPos, targetPos, 0.1f),speed);
if (startPos == targetPos)
{
_animationStarted2 = false;
Destroy(gameObject, 0.25f);
}
}

Related

localScale is not working at the runtime after applying the Animator component

I apply an animator component to my Game Object. After that when I play the game, I try to change the localScale of the game object but it doesn't work.
Here is my code to change the game object's localScale according to its direction on the x coordinate.
private Rigidbody2D rb;
private Vector3 direction;
private Animator anim;
private bool isLookingRight;
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
isLookingRight = false;
}
private void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
TurnDirection(horizontal);
}
// turns the player towards to movement direction
private void TurnDirection(float horizontal)
{
if (horizontal > 0 && !isLookingRight || horizontal < 0 && isLookingRight)
{
isLookingRight = !isLookingRight;
direction = transform.localScale;
direction.x *= -1;
transform.localScale = direction;
}
}
It worked well before applying the animation to the Game Object. I can't change the scale of the Game Object even manually on the inspector while playing the game.
This is probably caused by keyframes controlling localScale in the animation file. If you don't need it, you can solve the problem by deleting these keyframes from the animation window.
See here

Jump functionality for a 2D Top Down Unity game?

I am struggling to find an efficient way to let my player jump in a 2D Top Down world. I can see a lot of tutorials about platformer views where the camera is oriented at the side of the player, but nothing really working for a top down view like startdew Valley.
I am not using physics, so I move the character on the tilemap using a Couroutine which moves the player to the next position on grid, here it is my Update and DoMove methods:
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input.x != 0)
input.y = 0;
if (input != Vector2.zero)
{
animator.SetFloat("Horizontal", input.x);
animator.SetFloat("Vertical", input.y);
var targetPos = transform.position + new Vector3(input.x, input.y, 0f);
// obstacle detection
Vector3Int obstaclesMapTile = obstacles.WorldToCell(targetPos - new Vector3(0, .5f, 0));
if (obstacles.GetTile(obstaclesMapTile) == null)
{
StartCoroutine(DoMove(targetPos));
}
}
animator.SetFloat("Speed", input.sqrMagnitude);
}
}
private IEnumerator DoMove(Vector3 newPos)
{
isMoving = true;
while ((newPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, newPos, moveSpeed * Time.fixedDeltaTime);
yield return null;
}
transform.position = newPos;
isMoving = false;
}
Is there anybody which could give me an hint on how to add a jumping feature? ( ideally with animation support?) I am kind of running out of ideas.
Thanks in advance.
Just think of it as animation only. Since it is 2D top down, it's more about it looking like it jumps, and then if it has to go over something while in the jump animation, test for just that.
For example; if over hole and jump animation is playing, then allow movement over the whole, otherwise fall. So if the player presses the button for jump, the animation would play, and there should be some variable storing what animation the player is currently in.

Unity 2D Top-Down mouse facing weapon rotation problem

I am making a Top-Down 2D shooting game and i did spot a trouble.
The point is, player gun has weird rotation whenever the player rotate.
I made my Player face mouse position. Player gun is not in the center of sprite.
The Gun is a prefab in PlayerHand and PlayerHand is a Child of Player.
I tried a lot of things and yet still i cant find a solution.
public class HandHolder : MonoBehaviour
{
[SerializeField] Gun gun;
[SerializeField] float offsetX;
[SerializeField] float offsetY = 0.01f;
Gun playerGun;
void Awake ()
{
playerGun = Instantiate(gun,transform.localPosition,transform.localRotation) as Gun;
}
// Update is called once per frame
void Update ()
{
playerGun.transform.position = new Vector3(transform.position.x + offsetX,transform.position.y + offsetY);
playerGun.transform.rotation = transform.rotation;
playerGun.Shooting();
}
}
void Update()
{
if (!isLocalPlayer)
return;
Vector3 position = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * 20f;
transform.position += position;
FaceMouse();
}
public void FaceMouse()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
mousePosition.Normalize();
float rotation_z = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
Here are the screenshoots. My Player already has a gun in texture. but it is only texture. I want the Gun prefab to be exactly on the place of Player sprite gun, whenever i rotate.
add an empty to your player, name it gunTransform. tag it GunTransform make sure the forward axis(blue) is facing the players forward direction.
Class Level variable -
Transform guntransform;
in Awake():
guntransform=this.GameObject.FindObjectWithTag("GunTransform").getComponent<Transform>();
then instead of
playerGun = Instantiate(gun, transform.localPosition, transform.localRotation) as Gun;
call
playerGun = Instantiate(gun, guntransform.position, guntransform.rotation) as Gun;

Unity3d Move 2D Sprite relative to mouse position

if I move my sprite with the mouse, the sprite is always exactly under the cursor.
At the moment my code looks like that:
public GameObject player;
private float distance = 1;
private void Update()
{
if (Input.GetMouseButton(0))
{
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 playerPos = Camera.main.ScreenToWorldPoint(mousePos);
player.transform.position = playerPos;
}
}
but i want to move the sprite, no matter where my mouse courser is on the background. so if i click and hold next to the sprite and move my mouse to the right, i want that my sprite move the same way in same direction.
Example Picture
In this case, you should use a relative movement, that is, the amount that the mouse moved from its current position when the mouse button was clicked, as if that was the origin.
So, you should take note of the current mouse position when the user pressed the mouse button.
Here is one solution that does what I describe:
// by Vander 'imerso' Nunes to StackOverflow answer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseDrag : MonoBehaviour
{
public GameObject player;
bool dragging = false;
Vector3 mouseStartPos;
Vector3 playerStartPos;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
dragging = true;
mouseStartPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
playerStartPos = player.transform.position;
}
else if (Input.GetMouseButtonUp(0))
{
dragging = false;
}
if (dragging)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
Vector3 move = mousePos - mouseStartPos;
player.transform.position = playerStartPos + move;
}
}
}
You will notice that both current player position and current mouse position are noted when the button is initially pressed. So, they act as if they were the origin. The player is only moved by the distance that the mouse moves from its initial position when its button was pressed.

unity3d: Camera does not follow the player

I am fairly new in game development, I have a piece of code that makes camera move based on player's movement.
player's movement script:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
//to store movement
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLenghth = 100f;
//gets called regardless if the script is enabled or not
void Awake(){
floorMask = LayerMask.GetMask ("Floor");
playerRigidbody = GetComponent<Rigidbody> ();
//Input.ResetInputAxes ();
}
//unity calls automatically on every script and fire any physics object
void FixedUpdate(){
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
//Rotate ();
Turning ();
}
void Move(float h, float v){
movement.Set (h,0f,v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning (){
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (camRay,out floorHit,camRayLenghth,floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
}
and here is the script attached to the main camera:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
// a target for camera to follow
public Transform player;
// how fast the camera moves
public float smoothing = 4f;
//the initial offset from the target
Vector3 offset;
void start(){
//calculation of initial offset (distance) between player and camera
offset = transform.position - player.position;
Debug.Log ("offset is " + offset);
}
void FixedUpdate (){
//updates the position of the camera based on the player's position and offset
Vector3 playerCameraPosition = player.position + offset;
//make an smooth transfer of location of camera using lerp
transform.position = Vector3.Lerp(transform.position, playerCameraPosition, smoothing * Time.deltaTime);
}
}
but when I attach the script to my main camera, as soon as I play test the game camera starts to relocate and moves towards the ground even though the player hasn't moved yet. If I remove the script from the camera and make the camera the child of the player, as soon as I hit play, camera starts to rotate around the object.
Please give me some hints what am I doing wrong ?
The camera offset isn't being set because of the lower case on your start method. This means the offset remains at its default value which is 0,0,0 causing your camera to move to some funky place.
Change: `
void start() {
...
}
to
void Start() {
...
}
see you don't need any code for this just make you camera a child of your player object..
drag you camera object onto the player object in hierarchy