script malfunctioning when added to character - c#

I have a simple code that kicks the ball in the direction the player is facing, it worked fine when I tested it with a cube as player but,
now when I added the same script to player character it's only kicking the ball when it's all x, y, z rotation is zero
the code:
if (Input.GetKey(KeyCode.Space))
{
Vector3 kickDirection=playerfrount.position - playerback.position;
kickDirection = kickDirection.normalized;
Debug.Log(kickDirection);
//Vector3 forwardd = transform.forward;
carryingBallplayer = false;
rbb.AddForce(kickDirection * kickForceplayer, ForceMode.Impulse);
}
I am expecting that the player character kicks in the direction it's facing

Related

Unity: TopDown view - GameObject does not rotate toward mousepos

I've been doing some research on why my player(GameObject) is does not rotate toward my mouse position in my TopDown 3D game and I can't seem to find what is wrong with my code, so im making this post. The problem thats I have is that only the GameObject of my player (in my case, a capsule) rotate toward my mouse position but the axis of my player stays the same. In other word, I can't rotate the axis of my player, to face my mouse position, but I can rotate the GameObject of my player to face my mouse position. Its really hard to explain and this never happened to me before. Question is how can I rotate the axis of my player to face my mouse position. Keep in mind that my game is a top down view.
Here is the code im using for my playerMouvment and for my mouseLook:
public class Controller : MonoBehaviour
{
public float moveSpeed = 6;
Rigidbody rb;
Camera viewCamera;
Vector3 velocity;
void Start()
{
rb = GetComponent<Rigidbody>();
viewCamera = Camera.main;
}
void Update()
{
Vector3 mousePos = viewCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, viewCamera.transform.position.y));
transform.LookAt(mousePos + Vector3.up * transform.position.y);
velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized * moveSpeed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
Again I tried and look for any error in my code and I can't find anything that cause this weird situation and so if anyone can help me find a better way to write this code and solve my problem it would be great!
If I understand you correctly everything is fine with your game and the player is turning as it should, but only in the editor that the axis of the player (red, green and blue arrows) don't turn with the player?
If this is the problem it might be that you are using global space handle instead of local space. Clicking the icon I highlighted in the image should do the trick.
Use this code instead of LookAt() function
Vector2 direction = mousePos.position - player.transform.position;
player.transform.right /* Maybe you need Up or -Up or -right */ = direction;
This would work too in some cases
Vector2 direction = new Vector2
(
mousePos.position.x - player.transform.position.x,
mousePos.positoin.y - player.transform.position.y
)
player.transform.right /* Maybe you need Up or -Up or -right */ = direction;

How can I rotate an object to face a target?

My bat stays still in the air.
How can i check that the player, that is moving right below on x axis, comes from the left or right side relative to the bat?
public class Bat : MonoBehaviour
{
Player player;
void Start()
{
player = FindObjectOfType<Player>();
}
void Update()
{
if (transform.InverseTransformPoint(player.transform.position).x >= 0)
transform.rotation = new Quaternion(transform.rotation.x, 0f, transform.rotation.z, 0f);
else
transform.rotation = new Quaternion(transform.rotation.x, -180f, transform.rotation.z, 0f);
}
}
As you may notice i try to flip the the Bat so it actually looks at the player.
First, don't use new Quaternion(...); unless you absolutely, 100% know quaternions inside and out. For instance, having the w component be 0 results in zero effective rotation. Also, quaternions use unitless figures and not degrees for their components. See here for a nice visualization of what different quaternion values might look like, under Quaternion).
Second, your logic is weird because if the bat has zero (identity) rotation, and the player is on the left of the bat, then your logic tries to* flip the bat 180 degrees, so that the player is now on the right side of the bat.
Then, the next frame assuming the bat and player are still in the same positions, the logic says oh the player is on the right side, set the rotation to zero (identity) rotation, which is of course what it was in the first place. So basically, you would have the bat rotate 180 degrees again so that the player is once again on the left side of the bat.
And so, you could get into a situation where every frame, the bat would flip a complete 180. Definitely not desired.
* I'm assuming if you had used Quaternion.Euler(transform.eulerAngles.x, 0f, transform.eulerAngles.z) etc.
Instead of concerning with any of that, use Vector3.Cross to find the forward the bat should point so its right faces the player's position. Then, use Quaternion.LookRotation to set the rotation of the bat to point in that forward direction:
void Update()
{
Vector3 batRightDir = player.transform.position - transform.position;
Vector3 batForwardDir = Vector3.Cross(batRightDir, Vector3.up);
if (batForwardDir.sqrMagnitude == Vector3.zero)
{
// player above or below bat. do nothing?
return;
}
transform.rotation = Quaternion.LookRotation(batForwardDir);
}
If you have the player on a different z as the bat, this will cause the bat to rotate around the y axis accordingly, which is what you would want from a 3d game, and could be a neat effect for a 2d game if you want that kind of effect.
If you want it to ignore the z position of the player, you could zero out the z component of batRightDir...
void Update()
{
Vector3 batRightDir = player.transform.position - transform.position;
batRightDir.z = 0; // ignore Z differences between bat and player
Vector3 batForwardDir = Vector3.Cross(batRightDir, Vector3.up);
if (batForwardDir.sqrMagnitude == Vector3.zero)
{
// player above or below bat. do nothing?
return;
}
transform.rotation = Quaternion.LookRotation(batForwardDir);
}
or it may be more intuitive to branch as you were previously:
void Update()
{
Vector3 batRightDir = player.transform.position - transform.position;
if (batRightDir.x > 0)
{
transform.rotation = Quaternion.identity;
}
else if (batRightDir.x < 0)
{
transform.rotation = Quaternion.LookRotation(Vector3.back);
}
else
{
// player above or below bat. do nothing?
}
}
You can get the access to his Rigidbody and than call it.
If Rigidbody.velocity.x > 0 he is moving to the right. If it's <0 it's moving to the left. All is related to X axis of course.

Issue teleporting a character

I have an issue, I programmed a simple code to teleport the main character of my game from A position to B. The code works, but when the character touches the collider and teleport to the new position, it goes a little bit further than the position I need it to be and the character animations and horizontal movement stop working.
The rigidbody, triggers of my controller, and general values of movement and physics doesn't change the only values that change are x transform position and y transform position:
private void OnTriggerEnter2D(Collider2D collision){
if (collision.tag == "Transporter"){
transform.position = new Vector3(collision.transform.position.x, transform.position.y + 1, transform.position.z);
rb.velocity = new Vector3(0, 0, 0);
}
}

Unity jittery movement

I have the following simple lines of code that moves the camera similar to the camera movement in zig zag game ( moving vertically forever ). I also have very simple cube structure similar to zig zag game. In original zig zag game, there is no jittery movement in iPad Mini. But the below lines of code causing jittery movement..
I tried project settings->Time setting to 0.03 and targetFrameRate to
Tried in Update
Tried in FixedUpdate
Tried in LateUpdate...
But none works, I can always reproduce the jittery movement
void Update() {
float calculatedSpeed = speed * Time.deltaTime;
transform.Translate( direction * calculatedSpeed);
}
void LateUpdate() {
if( !dead ) {
Vector3 position = transform.position;
float halfX = position.x;
float halfZ = position.z;
float distance = Vector3.Distance (position, playerInitPosition);
Vector3 newPos = Main.Instance.camReference.forward * distance;
Main.Instance.camReference.position = newPos;
}
}
In Update, transform.position updates player move in zig zag pattern,
In LateUpdate, camera moves vertically based on the distance the player moves
You can check android game play here:
https://play.google.com/store/apps/details?id=com.angryeggstudio.games.zigzagpenguin
This smoothness is not there in iPad Mini
Update 1:
Android that works without any flaw...its smooth and fine :
iPad Mini that has jittery movement:
Note: Check the cube edges while camera moves... you can spot its jittery movement in iPad Mini...

character keeps shaking while in topdown shooter

ok well i am working on a top down shooter i have made my character look at the mouse using screentoworld view and i made my camera follow my players x, and z axis but anytime my character moves parallel from the mouse it starts shaking I think its because it looks at the mouse an the mouse real world position is dependent on the cameras position which is, but i am not sure.
here is the playerscript the many backslashes showed other things I've tried
gameObject.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal")*movementspeed,0,Input.GetAxisRaw("Vertical")*movementspeed);
if (gameObject.GetComponent<Rigidbody> ().velocity.x != 0 && gameObject.GetComponent<Rigidbody> ().velocity.z != 0) {
gameObject.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal")*movementspeeddiag ,0,Input.GetAxisRaw("Vertical")*movementspeeddiag);
}
// makes vector 3 type target equall to mouse position on pixial cordinates converted in to real world coordniates
target = camera.ScreenToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.transform.position.y - transform.position.y));
//Vector3 newtarget = target - transform.position;
//lerptarget = Vector3.Lerp (transform.eulerAngles,newtarget, 100);
// states the vector 3 values of target
// makes object local z face target and iniziates up axis
//Quaternion rotation = Quaternion.LookRotation (newtarget, Vector3.up);
//transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle (transform.eulerAngles.y, rotation.eulerAngles.y, rotatespeed * Time.deltaTime);
transform.LookAt (target,Vector3.up);
and camera script
void LateUpdate(){
position = new Vector3 (player.transform.position.x, 10, player.transform.position.z);
transform.position = position;
//transform.localPosition = Vector3.Lerp (transform.position, position, speed *Time.deltaTime);
transform.eulerAngles = new Vector3 (90,0,0);
}
Probably, the problem is that you change the velocity of rigidbody. Becouse velocity changes applied each fixed update time interval, it doesnt match with frame updating time, and may lead to shaking. According to unity docs you should try to avoid directly changes of velocity. (http://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html)
I'd suggest you to you use MovePosition alongside with Lerp function to implement player movement.
See this:
http://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Categories

Resources