How To: Make a Rotating Lazer Offset In Unity3D? - c#

I'm attempting to create an effect similar to the one found in this video:
https://www.youtube.com/watch?v=1i0da_Pg5Jc
However, with verbatim code it does not function as demonstrated. I'm not sure if it's changes in unity or failure on my part but I'm using the same shader, and probably have watched this video like.. Oh Idk, 2501 times.. and I can't does it.
The best I can do is back and forth, Time.time does not work for me.
The code suggested..
Vector2 m_Offset = new Vector2(0, Time.time);
Doesn't do anything.
What I'm rolling with right now is..
void ProcessTextureShift()
{
m_MaterialOffsetValue += m_OffsetShiftValue * Time.deltaTime;
if (m_MaterialOffsetValue >= m_MaterialOffsetLimit)
ResetMaterialOffset();
m_WeaponBeam.material.
mainTextureOffset = new Vector2(0, m_MaterialOffsetValue);
}
That produces an effect from start to finish but I was trying to accomplish the rotating/spinning of the rainbow in the video.
float m_MaterialOffsetLimit = 1.0f;
float m_MaterialOffsetValue = 0.0f;
float m_OffsetShiftValue = 2.0f;

Related

How to do vector addition in Unity

This is my first from scratch game project. I'm trying to make a pinball game but I don't want to just "watch a video on how to make a pinball game". I want to run into the problems and learn how to tackle them as they come.
So far, attaching script to a sprite was issue #1 but I've kinda worked that out. Issue #2 was creating variables and having them translate to real object values. After multiple hours of trial and error I eventually just copied someone elses script that had the most basic setup possible, then broke it and rebuilt it to what I have below with the addition of void Update.
My question is mostly to gather a better understanding but also about a new problem of mine.
Issue #3 is currently when I click play, it moves the object only once. I thought void update is supposed to call every frame?
I would also like to know why when I do transform.position, why can't I do transform.position += (value 1, value 2)? From what I've come up with from experimenting, the only way to alter transform.position is to do = new Vector everytime which I don't fully understand... Another way of wording this part of the question would be: Is there a shorter way of writing a vector transformation or is this the only way the change can be written?
Below is the code. I appreciate any answers even if it's simply directing on the right path to find the information I want.
public float width, height, xSpeed, ySpeed, xPosition, yPosition;
public Vector2 position, scale;
void Start() {
// Initialise the variables
width = 0.5f;
height = 0.5f;
xSpeed = 0;
ySpeed = -1f;
xPosition = 0;
yPosition = 3.5f;
// set the scaling
Vector2 scale = new Vector2(width, height);
transform.localScale = scale;
// set the position
transform.position = new Vector2(xPosition, yPosition);
}
void Update() {
transform.position = new Vector2(xPosition + xSpeed,
yPosition + ySpeed);
}
First I would recommend you changing the title of the question to something that is a bit more on point, so that people have an idea what programming concept your question is about! :) I would recommend something like "How to do vector addition in Unity".
I will go through your questions one-by-one:
Yes, the Update-Function is called every frame! With each call of Update() you set your position to exactly the same value again and again. That is why it is not moving. Neither the xPosition/yPosition nor the xSpeed/ySpeed variables are changing after they have been defined in Start(), so your Update Function will always set your position to (0, 2.5, 0).
You can do Vector addition! But in order to do that, you need to properly write it in your code, by which I mean you need to make a vector out of the values you want to add and only then you can add them to the position vector! So if you wanted to add the xSpeed/ySpeed values ontop of your position, it would look like that:
transform.position += new Vector2(xSpeed, ySpeed);
I hope that helps!
With the help of Jayne, this is what the code ended up turning into, hope this helps anyone else who just wants a straightforward way to alter a vector:
public float width, height, xSpeed, ySpeed, xPosition, yPosition;
public Vector2 position, scale;
void Start() {
// Initialise the variables
width = 0.5f;
height = 0.5f;
xSpeed = 0;
ySpeed = -0.01f;
xPosition = 0;
yPosition = 3.5f;
// set the scaling
Vector2 scale = new Vector2(width, height);
transform.localScale = scale;
// set the position
transform.position = new Vector2(xPosition, yPosition);
}
void Update() {
// Move the pinball
xPosition += xSpeed;
yPosition += ySpeed;
transform.position = new Vector2(xPosition, yPosition);
}

Smoothing player movement and speed

I know this question is already asked a few times, but didn't find it in the way of my code.
In the movement of my playerObject I consider the direction the Camera is looking to atm.
What I want to do is to slow down the speed of the movement, but it doesn't work with the walkSpeed I use.
I also want to smooth the movement (start and end).
public void UpdateMovement()
{
Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); //In targetDir the direction the Player wants to move to is saved -> player presses W means forward
// targetDir = Vector2.ClampMagnitude(targetDir, 1);
Vector3 camForward = cam.forward; //camForward saves the direction, the cam is looking actually
Vector3 camRight = cam.right; //camRight saves the actual right side of the cam
camForward.y = 0.0f; //y=0 because we don't want to fly or go into the ground
camRight.y = 0.0f;
camForward = camForward.normalized;
camRight = camRight.normalized;
transform.position += (camForward * targetDir.y + camRight * targetDir.x) * walkSpeed * Time.deltaTime;
I'm not sure exactly about what the context of what you're trying to do here is, but I think you're looking for Vector2.Lerp().
The way you use it is to first calculate a target position as a Vector. So,
Vector2 target = new Vector2(targetX, targetY)
I'll let you figure out what targetX and targetY are, based on wherever you're trying to move the thing you're moving.
Then you would come up with the speed, which is what you're pretty much already doing. Like so:
float speed = walkSpeed * Time.deltatime;
Finally, instead of setting the position directly, you use the Lerp function instead.
transform.position = Vector2.Lerp(transform.position, target, speed);
I didn't test any of this, and just wrote it on the fly, but I'm pretty sure this is what you're looking for.
I wrote a script you can try to create a cube, I'm sorry because I'm also a unity3d newbie, but I hope it helps you
private Transform player;
Vector3 toposition;//interpolation
void Start(){
player = this.transform;
toposition = new Vector3(0,5,0);
}
// Start is called before the first frame update
void Update(){
if(Input.GetKey(KeyCode.W)){
UpdateMovement();
}
}
public void UpdateMovement(){
player.transform.position = Vector3.Lerp(transform.position, toposition, Time.deltaTime * 5f);
}

Handling mouse for first person game in monogame

I am trying to make a first-person game on Monogame and so far all I have come with or found on the internet didn't meet my standards.
this is how I am currently handling the mouse:
private void HandleMouse()
{
Vector2 mouseDifference;
mouseNow = Mouse.GetState();
if (mouseNow.X != mouseDefaultPos.X || mouseNow.Y != mouseDefaultPos.Y)
{
mouseDifference.X = mouseDefaultPos.X - mouseNow.X;
mouseDifference.Y = mouseDefaultPos.Y - mouseNow.Y;
leftrightRot += mouseSens * mouseDifference.X;
updownRot += mouseSens * mouseDifference.Y;
Mouse.SetPosition((int)mouseDefaultPos.X, (int)mouseDefaultPos.Y);
UpdateViewMatrix();
}
}
private void UpdateViewMatrix()
{
Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
viewMatrix = Matrix.CreateLookAt(new Vector3(0,0,0), cameraRotatedTarget, cameraRotatedUpVector);
}
My problem is that while this solution works, it is extremely inconsistent when it comes to how far the camera should rotate.
for example, happens when I make circles with the mouse and see that sometimes the mouse randomly jumps more than expected.
My main assumptions inconsistencies in fps that cause the time between frames to change, thus affecting the distance the mouse can move within that time.
I don't know if this is the reason or if my assumption can even cause this, but I would like to find a way to get consistent mouse movement.
I can provide a video of the problem if needed.
Thank you in advance.
The mouse in Windows is updated 240 times per second. The game loop runs at 60 frames per second. The discrepancy can lead to large mouse deltas. The solution is to limit the change in the mouse delta:
Vector2 mouseDifference;
const float MAXDELTA = 6; // Set to the appropriate value.
mouseNow = Mouse.GetState();
if (mouseNow.X != mouseDefaultPos.X || mouseNow.Y != mouseDefaultPos.Y)
{
mouseDifference.X = Math.Min(MAXDELTA, mouseDefaultPos.X - mouseNow.X);
mouseDifference.Y = Math.Min(MAXDELTA, mouseDefaultPos.Y - mouseNow.Y);
leftrightRot += mouseSens * mouseDifference.X;
updownRot += mouseSens * mouseDifference.Y;
Mouse.SetPosition((int)mouseDefaultPos.X, (int)mouseDefaultPos.Y);
UpdateViewMatrix();
}
This is an old thread, but I figured I would share a solution. The solution that's worked for me to use the GameTime object to relate how much the player should rotate by. In other words, rotate by (delta * rotationSpeed * GameTime.ElapsedTime.TotalSeconds) so that each rotation is relative to how much time has passed since the last frame. This protects it against frame drops, which I've found has been the problem for me.

Make time measuring independent of FPS (2D C#)

Lets say I'm working in a 2D plane, with a person in the bottom of my screen, and an object that moves down along the Y-axis.
The moving object has following movement code:
transform.position += new Vector3 (0, -1, 0) * speed * Time.deltaTime;
Now, as I want to be able to modify how long it takes for the object to connect with the player, I created this, where spawnTimeDistance is our key factor:
Instantiate (obstacle, player.transform.position + new Vector3(-0.50F , (spawnTimeDistance + obstacleDimensionY + pScript.playerDimensionY), -1), Quaternion.identity);
As can be seen, spawnTimeDistance is a place-holder for the objects Y-distance to the player. However, using this code I get great inconsistencies with my results, especially when comparing devices. I suspect this is caused by distance being FPS dependant, instead of actual time dependant.
To fix this I believe I should implement Time.deltaTime in an extended manner, but I'm insecure on how.
EDIT - spawnDistanceTime related:
void Start() {
spawnTimeDistance = 4F;
}
and
Vector2 sprite_size = obstacle.GetComponent<SpriteRenderer> ().sprite.rect.size;
Vector2 spriteScale = obstacle.transform.localScale;
float sizeAndScaleY = sprite_size.y * spriteScale.y;
float obstacle_local_sprite_sizeY = (sizeAndScaleY / obstacle.GetComponent<SpriteRenderer> ().sprite.pixelsPerUnit) * 0.5F;
obstacleDimensionY = obstacle_local_sprite_sizeY;
Above code, same thing for my player.
Edited the Instantiate to include the obstacleDimensions, had them removed before as I thought it would give a simpler question.

Stop sprite from bouncing

I am making a simple puzzle game on the Unity platform. First, I tested some simple physics on scratch and then wrote it in C#. But for some reason, some of the code isn't producing the same effect. In scratch, the code makes the sprite do exactly what I want; go towards the mouse, slow down, then stop on the mouse. However, (what I presume to be) the same code in Unity makes the sprite go crazy and never stop.
UPDATE
It definitely is cause #2. It turns out the sprite is bouncing off other bounding boxes, causing the velocity to change drastically. It would work with smaller values, except I have gravity. My new question is there any way to stop the sprite from bouncing?
Vector2 CalcHookPull(){
//code for finding which hook and force
//find if mouse pressed
if (Input.GetMouseButton(0))
{
//check if new hook needs to be found
if (!last){
Vector2 mypos = new Vector2(transform.position.x, transform.position.y);
Vector2 relmousepos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x-transform.position.x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y-transform.position.y);
//player is on layer 8, don't want to check itself
int layermask = ~(1<<8);
RaycastHit2D hit = Physics2D.Raycast(mypos, relmousepos, Mathf.Infinity, layermask);
maybeHook = hit.collider.gameObject;
}
if(maybeHook.tag == "hook"){
float hookx = maybeHook.transform.position.x;
float hooky = maybeHook.transform.position.y;
float myx = transform.position.x;
float myy = transform.position.y;
//elasticity = 30
float chx = (hookx - myx) / (5f + 1f/3f);
float chy = (hooky - myy) / (5f + 1f/3f);
float curchx = GetComponent<Rigidbody2D> ().velocity.x;
float curchy = GetComponent<Rigidbody2D> ().velocity.y;
Vector2 toChange = new Vector2 (curchx * 0.3f + chx, curchy * 0.3f + chy);
Debug.Log(toChange);
last = Input.GetMouseButton (0);
return toChange;
} else{
last = Input.GetMouseButton (0);
return new Vector2(0,0);
}
} else {
last = Input.GetMouseButton (0);
return new Vector2 (0, 0);
}
}
Possible differences:
Vectors work differently that xy changes (doubtful)
The bounding box is not allowing the sprite to go all the way to the center of the hook object. (likely, but don't know how to fix)
I copied the code wrong (unlikely)
Any help is appreciated, thanks!
I was being stupid. There is already something for this. Should have thought it through more. http://docs.unity3d.com/Manual/class-PhysicsMaterial2D.html

Categories

Resources