Get Unity Blend Tree to update based on player rotation (mouse position) - c#

I'm working on the animations for a character in a top down game. I got the animations to work when the player is moving forwards towards the top, however, whenever I rotate the player with the mouse (to aim) the forward animation is now left/right, etc, etc. I'm using Unity3d and C# with blend tree animations.
The code I'm using is straightforward:
animator.SetFloat("VelX", playerInput.Horizontal);
animator.SetFloat("VelY", playerInput.Vertical);
I can't figure out how to make the forward animation play whenever I'm moving TOWARDS the mouse position.
My Solution:
var heading = Input.mousePosition - this.transform.position;
var distance = heading.magnitude;
var dir = heading / distance;
animator.SetFloat("VelX", playerInput.Horizontal * Mathf.Cos(dir));
animator.SetFloat("VelY", playerInput.Vertical * Mathf.Sin(dir));
Any help would be appreciated.

You may have figured this out already but I just had the same issue and I just found out a way to do this. Hopefully it helps others.
Vector3 inputVector = (Vector3.forward * Input.GetAxis("Vertical")) + (Vector3.right * Input.GetAxis("Horizontal"));
Vector3 animationVector = _playerModel.transform.InverseTransformDirection(inputVector);
var VelocityX = animationVector.x;
var VelocityZ = animationVector.z;
this._playerAnimator.SetFloat("x", VelocityX);
this._playerAnimator.SetFloat("z", VelocityZ);
I my case I have my movement script on a parent empty object. This object rotates the child player model, which is the one getting animated. If you do this then you will need to reference the player model like I am doing. Otherwise you can you transform if you are using the parent object.
I am using a character controller on my parent object not a rigidbody, but it may work the same either way.
From my understanding the key part is 'InverseTransformDirection' which is taking my physical world horizontal and vertical vectors and then converting them based on the rotation of my player model. This then makes the movements be relative to the players rotation rather than the worlds rotation and I can move backwards or strafe correctly as I am moving my mouse for rotation and wasd for movement.

Related

Using a Custom rotation in "Instantiate" - Unity 3D

I'am trying to make a throwing spear mechanic in my game.
The problem is that when i instantiate/spawn my "spear" its not facing the right direction i want it to be facing, forward in a 90 degree angle in the X and Y rotation. I tried to give it a rotation like this:
Instantiate(Spear.GetComponent(), transform.position, Quaternion.Euler(0,90,90));
but this only works if the player is in a specific position on the map (look image).
this is the code i have now:
clone = Instantiate(Spear.GetComponent<Rigidbody>(), transform.position,
Quaternion.Euler(0,90,90));
clone.velocity = transform.TransformDirection(Vector3.forward * ThrowForce);
You should give the rotation in the spear prefab and then just normally spawn it based on the prefab rotation like
Instantiate(Spear, position, Spread.rotation)
or if this doesnt work you can look at this
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html

Off-center rotate object in Unity

I have a laser turret in Unity3D, which I'd like to turn towards the enemies. The turret consists of a "leg" and a "head" (selected on the picture 1). The head can pan and tilt around a spherical joint.
I do the following:
Vector3 targetDir = collision.gameObject.transform.position - turretHead.transform.position;
float step = turnSpeed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(turretHead.transform.forward, targetDir, step, 0.0f);
turretHead.transform.rotation = Quaternion.LookRotation(newDir);
The problem is that since the pivot of the head is not aligned with the laser beam, the turret turns into the almost right direction, but it shoots above the target. (It would hit perfectly, if the laser would come out of the red axis of the pivot.)
Is there a builtin method or some trick to achieve the correct functionality other then doing the calculation myself?
Okay, here's the quick and easy way to do this. It's probably "better" to do it with proper trig, but this should give you the result you want pretty quick:
If you don't already have a transform aligned with the barrel, then create an empty GameObject and line it up (make sure it's a child of the turret so they move together). Add a reference to your script for it's transform.
Then, in your first line, calculate from the new Barrel transform instead of the turretHead transform. Leave everything else the same. This way it calculates from the turret barrel, but moves the turret head.
Now, this approach isn't perfect. If the pivot center is too offset from the barrel transform, then it would be less accurate over large moves, or when aiming at something close by, because the expected position when aiming would be different than the initial position due to the rotation pivot being elsewhere. But this can be solved with iteration, as the calculation would become more accurate the closer it is to it's desired goal.

Rotating 2D world within Unity

I am looking at developing a game within Unity by using C#
The game will take the gyroscope orientation and rotate accordingly to the direction of which the phone is rotated.
I am curious of how this would work, I understand how I would be able to read and update the gyroscope orientation however I am unsure on how to assign this to a world to rotate. There will be a player on world which will be the next challenge to prevent the player clipping through the world when it is rotated.
Hence the world should rotate around the players current location.
I currently have no code as I am in the process of designing this, however i am unable to get the logic of how to make this work within my head
Thankyou
If I get your objective right, I guess rotating the camera like in a Fist-Person game should be enough, and would be way simpler than rotating the whole world while keeping the player static.
This is how I would go about it, first I wouldn't rotate the world, as that is alot of objects to rotate, but if you really wanted to you could parent all of the world to a single game object, then rotate that object about an axis based off of the players position(See this: https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html).
The simplest way is to attach your main camera to your player(Drag and drop it on your Player Object in your hierchy), then rotate your player.
for an example you can test on your machine without the gyroscrope:
using UnityEngine;
public class rotatorScript: MonoBehaviour {
void Update() {
// Will Rotate based off of left/right arrows
float rotator = -Input.GetAxisRaw("Horizontal");
// Move up or down based off of up/down Arrows
float verticalDirection = Input.GetAxisRaw("Vertical");
// Do the actual movement... using space.self so it is based on the player not the world.
transform.Translate(Vector3.up * verticalDirection * Time.deltaTime * 5f, Space.self);
transform.Rotate(0f,0f,90f * Time.deltaTime * rotator);
}
}
This script would be attached to the player.

Rotate an object according to terrain in Unity (C#)

I currently have an item placement system for building. It works by instantiating a "ghost" of the object that shows where it can be placed, the ghost (semi-transparent) object is attached to the camera and instantiates the object in its place when the player clicks.
I get the position at which to keep the ghost object like so:
var pos = transform.position + transform.forward * placeDistance; // A position 'someDistance' in front of the player
pos.y = Terrain.activeTerrain.SampleHeight(pos); // Get the position at the surface of the terrain to place the object
firePlaceable.transform.position = pos + Vector3.up * 0.001f; // 'halfHeight' is used in case the pivot is not on the base
Now.. I need the object to rotate according to the terrain so that the fire place is placed more or less correctly rotated. Any ideas? What would the best plan be?
Use the terrain normal vector at the place' position.
For example you could do a raycast straight down from the fireplace. The resulting hit contains a normal that is your place' up vector.
By thinking of it... I assume you already doing a raycast to get the position to place the fireplace right?
Use the placement raycast to get the up vector instead of making a new one.
So basicly do
fireplace.transform.up = clickPlaceHit.normal;

How to rotate a GameObject around another object according to the mouse cursor position in C#

I'm trying to rotate an object based on mouse cursor movement(like bubble gun in bubble shooter game). But I'm Filed to do that with my script.
MY script is :
mouse_pos = Input.mousePosition;
Debug.Log(mouse_pos);
object_pos = Camera.main.WorldToScreenPoint(target.position);
mouse_pos.x = mouse_pos.x - object_pos.x;
mouse_pos.y = mouse_pos.y - object_pos.y;
angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0,-angle);
It rotates only its same position it won't move.
Please any one help me to solve this. Or point me to any good tutorial ....
If I understand your problem correctly, then the object's transform is rotating around it's local origin, which is why you are seeing the correct rotation but no translation.
Unity applies transformations in the following order: scale, translate, rotate.
The easiest way to solve the problem is to parent your object's transform to another parent transform and rotate the parent transform instead (having applied a translation to your object's transform). Note that you will have to modify any scaling or translation on your object's transform because it will now be inheriting the parent transform's rotation.
Hope that helps, otherwise please provide more detail on your problem.

Categories

Resources