Click based movement not working - c#

I have the player moving towards where i have clicked. But when i arrive at the position of where i clicked, the sprite just flickers back and forth. I assume its because the sprite is going past this point, going back to it, going past it again, then going back constantly creating a 'flickering'. Any ideas why?
****SOLVED********
***UPDATED CODE***
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace AsteroidAvoider
{
class Player
{
public Vector2 position, distance, mousePosition;
public float speed;
public float rotation;
public Texture2D playerImage;
public MouseState mouseState;
public Player(Texture2D playerImage, Vector2 position, float speed)
{
this.playerImage = playerImage;
this.position = position;
this.speed = speed;
}
public void Update(GameTime gameTime)
{
mouseState = Mouse.GetState();
float speedForThisFrame = speed;
if (mouseState.LeftButton == ButtonState.Pressed)
{
mousePosition.X = mouseState.X;
mousePosition.Y = mouseState.Y;
}
if ((mousePosition - position).Length() < speed)
speedForThisFrame = 0;
if ((mousePosition - position).Length() > speed)
speedForThisFrame = 2.0f;
distance = mousePosition - position;
distance.Normalize();
rotation = (float)Math.Atan2(distance.Y, distance.X);
position += distance * speedForThisFrame;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(playerImage, position, null, Color.White, rotation, new Vector2(playerImage.Width / 2, playerImage.Height / 2), 1.0f, SpriteEffects.None, 1f);
}
}
}

The normalized vector , if I remember correctly should always have a total length of 1 (Vector2.Length() returns the length of the entire vector2 by the way)
A simple solution would be making your unit reduce the speed of movement if within the range of the mouse , for example
float speedForThisFrame = speed;
if((mousePosition-position).Length() < speed) speedForThisFrame = (mousePosition-position).Length();
and use speedForThisFrame for the position offsetting.

You need a collider, a Rectangle that represents your player, so when this collider contains your mousePosition or the click coordinate (you can easily detect it using Rectangle.Contains method) you simply set player's speed as 0, avoiding the flickering.
Of course, when the clicked coordinate changes, you have to set the previous player's speed.

Related

Unity3D how to make an object start moving in an arc or circle using radius?

Unity3D, C#
I would like to know how to move the object smoothly using radius, I want the object to start moving in a circle from the transform.position, like this:sample of what I want to do, and only using C# script, what I can think of is using transform like below.
timeCounter += Time.deltaTime * speed;
float x = Mathf.Cos(timeCounter) * width;
float z = Mathf.Sin(timeCounter) * height;
transform.position = new Vector3(x, 0, z);
I have tried this https://forum.unity.com/threads/how-to-make-an-object-move-in-a-circular-motion-at-constant-speed.526107/ but it is not what I wanted, the answer of mine (https://youtu.be/V2A-0yOUNwc) make the object quickly move to the right and it uses the middle location as the center then starts moving from the right, and I can't control which angle it will start.
Try Transform.RotateAround:
using UnityEngine;
public class RotateAround : MonoBehaviour
{
public Vector3 rotatingPoint;
private Vector3 rotAxis = new Vector3(0,1,0);
void Start()
{
}
void Update()
{
transform.RotateAround(rotatingPoint, rotAxis, 1f);
}
}
Check the documentation. You set the rotation poiunt,the rotation axis and the angle and that is it.

trying to make a mouse rotation script in unity, but it does nothing

Im making a 3d platformer In unity as my first game, and I'm trying to add some mouse rotation, but don't know what to do. the problem is it literally will not rotate.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PCM : MonoBehaviour
{
public float speed = 10.0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float translation = Input.GetAxis("MouseX") * speed;
float straffe = Input.GetAxis("MouseY") * speed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
}
}
all player propeties
I assume, since you said "platform" that you're doing 2D. You had
transform.Translate(straffe, 0, translation);
Usually, 2D works on X- (left/right) and Y- (up/down) axes (and Z is "in/out"). Try
transform.Translate(straffe, translation, 0);

How to launch an instantiated object in a certain direction from the center of the screen based on the mouse pointer position?

I am creating a simple game where you are locked in the center of the screen and must shoot things as they move toward you. The problem I am currently facing is that I can not launch a bullet in the direction of my mouse cursor. Currently, my code looks like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour {
PlayerScript playerScript;
public float xVel;
public float yVel;
public float direction;
private void Awake()
{
playerScript = FindObjectOfType<PlayerScript>();
//playerScript.AngleDeg is the direction the player is facing (based on mouse cursor)
transform.rotation = Quaternion.Euler(0, 0, playerScript.AngleDeg);
direction = transform.rotation.z;
//from the unit circle (x = cos(theta), y = sin(theta)
xVel = Mathf.Cos(direction * Mathf.PI);
yVel = Mathf.Sin(direction * Mathf.PI);
}
void Update () {
transform.position += new Vector3(xVel,yVel,0);
}
}
currently, when I run the code, the bullet shoots at an angle which is at the direction that is correct when the player is orientated sideways, but when orientated vertically is a full 45 degrees off.
Attach this as a component to your instantiated bullet object and it should work.
Transform playerTransform;
float bulletSpeed;
Vector3 directionToShoot
void Start()
{
playerTransform = FindObjectOfType<PlayerScript>().gameObject.transform;
bulletSpeed = 3f;
//Direction for shooting
directionToShoot = playerTransform.forward - Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
void Update()
{
//shoot
transform.Translate(directionToShoot * bulletSpeed * Time.deltaTime);
}

How do i make it into a smooth camera? (unity C# programming)

This is what i got and why does this website want me to put more explaining when i clarified above well i want to achieve a smooth camera control where the player is in the middle of the camera if the mouse is in the middle but as it moves toward a direction i want the camera to move just a little bit to reveal terrain (here i have 2 problems:
1.The camera doesnt move if the mouse is at the point 0,0 of the screen and i want it to be the center of the camera
2. the camera drifts away in that direction, it doesnt stop like i want to make it):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
// Camera cam = Camera.main.orthographicSize;
//Vector2 camcenter = new Vector2(cam * 2, camheight);
public GameObject mage;
private Vector3 offset;
public float mincam = 30f;
public float maxcam = 120f;
public bool mouse_smooth_cam = false;
// Update is called once per frame
void LateUpdate ()
{
offset = Input.mousePosition / 100 + transform.position - mage.transform.position;
transform.position = mage.transform.position + offset;
}
void Update()
{
HandleZoom();
}
private void HandleZoom()
{
float scrollValue = Input.mouseScrollDelta.y;
float newCamSize = Camera.main.orthographicSize - scrollValue*4;
Camera.main.orthographicSize = Mathf.Clamp(newCamSize, mincam, maxcam);
}
}
Instead of Input.mousePosition / 100 use Camera.main.ScreenToWorldPoint(Input.mousePosition)
also always use Time.deltaTime in Update methods
var PAN_SPEED = 30f;
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
offset = mousePos + transform.position - mage.transform.position;
transform.position = mage.transform.position + offset * Time.deltaTime * PAN_SPEED;

Tilt GameObject from side to side

I'm having a play with Google Cardboard. I am sitting in a cockpit and I can look around it with no problem.
Now I want to tilt my cockpit from side to side to give a more realistic feel rather than just being stationary.
So far I have this:
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour
{
float speed = 0.25f;
void Update()
{
Tilter ();
}
void Tilter()
{
if (transform.rotation.z < 5f) {
transform.Rotate (new Vector3 (0f, 0f, speed));
}
if (transform.rotation.z > 5f)
transform.Rotate (new Vector3 (0f, 0f, -speed));
}
}
This starts tilting the cockpit to the left as expected, but once the rotation gets bigger than the value of 5, the cockpit does not rotate the other way, it keeps rotating the same way, instead of the opposite direction.
I have not tried this code, but if I understand what you are trying to do, I would suggest to use Mathf.Sin and Time.time to continuously get values in the range of -1 to 1 and then multiply for the rotating range of your cockpit. For example:
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour
{
float speed = 1.0f;
float rotationAngle = 45;
void Update()
{
Tilter ();
}
void Tilter()
{
float rotationZ = rotationAngle * Mathf.Sin(Time.time * speed);
transform.Rotate (new Vector3 (0f, 0f, rotationZ ));
}
}
This example should slowly rotate your cockpit from 0 to 45, then back to 0, then to -45, then back to 0, an so on (again I have not tried it).
You can increase or decrease the value of speed to make the rotation faster or slower.

Categories

Resources